webAPi OData的使用

2023-05-06,

一、OData介绍

开放数据协议(Open Data Protocol,缩写OData)是一种描述如何创建和访问Restful服务的OASIS标准。

二、OData 在asp.net mvc中的用法

  1、在vs中新建webApi项目

2、添加测试类型

 public class Product
{
public int Id { get; set; } public string ProductName
{
get; set;
}
}

3、开启EF自动迁移,添加EF上下文,

namespace ODataTest.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using ODataTest.Models; internal sealed class Configuration : DbMigrationsConfiguration<ODataTest.Models.EFContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
} protected override void Seed(ODataTest.Models.EFContext context)
{
// This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. }
}
}
 public class EFContext : DbContext
{ static EFContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFContext, Configuration>());
}
public EFContext() : base("DefaultConnection")
{
} public DbSet<Product> Products { get; set; }
}

4.在数据库添加一些测试数据

Id ProductName
21 产品1
22 产品2
23 产品3
24 产品4

5、在Controllers文件夹添加OData控制器

6、vs将自动生成基本的CURD,

将GetProducts方法的EnableQuery特性的AllowedQueryOptions属性设置为:允许所有查询AllowedQueryOptions.All

    public class ProductsController : ODataController
{
private EFContext db = new EFContext(); // GET: odata/Products
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<Product> GetProducts()
{
return db.Products;
} // GET: odata/Products(5)
[EnableQuery]
public SingleResult<Product> GetProduct([FromODataUri] int key)
{
return SingleResult.Create(db.Products.Where(product => product.Id == key));
} // PUT: odata/Products(5)
public IHttpActionResult Put([FromODataUri] int key, Delta<Product> patch)
{
Validate(patch.GetEntity()); if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} patch.Put(product); try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
} return Updated(product);
} // POST: odata/Products
public IHttpActionResult Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} db.Products.Add(product);
db.SaveChanges(); return Created(product);
} // PATCH: odata/Products(5)
[AcceptVerbs("PATCH", "MERGE")]
public IHttpActionResult Patch([FromODataUri] int key, Delta<Product> patch)
{
Validate(patch.GetEntity()); if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} patch.Patch(product); try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
} return Updated(product);
} // DELETE: odata/Products(5)
public IHttpActionResult Delete([FromODataUri] int key)
{
Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} db.Products.Remove(product);
db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent);
} protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
} private bool ProductExists(int key)
{
return db.Products.Count(e => e.Id == key) > ;
}
}

7、在WebApiConfig类的Register方法里面注册OData路由

using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using ODataTest.Models; ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

8、运行网站就可以在浏览器就行OData的API测试

  常用查询:

  查询所有:http://localhost:64643/odata/Products

  根据主键进行查询:http://localhost:64643/odata/Products(22)  【22为主键值】

  相等查询:http://localhost:64643/odata/Products?$filter=ProductName eq '产品1'

只查询部分字段:http://localhost:64643/odata/Products?$select=Id

  模糊查询(这个找了老半天):http://localhost:64643/odata/Products?$filter=substringof('品1',ProductName) eq true  

  还有更多的查询,参考,http://www.odata.org/documentation/odata-version-3-0/url-conventions/ ,在mvc中使用EF和OData基本能够满足所有的前端查询,有利于快速开发API查询接口

webAPi OData的使用的相关教程结束。

《webAPi OData的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。