webAPi OData的使用

匿名 (未验证) 提交于 2019-12-02 22:10:10

一、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) > 0;         }     }

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?$filter=ProductName eq '产品1'

  还有更多的查询,参考,http://www.odata.org/documentation/odata-version-3-0/url-conventions/

文章来源: webAPi OData的使用
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!