一、OData介紹 開放數據協議(Open Data Protocol,縮寫OData)是一種描述如何創建和訪問Restful服務的OASIS標準。 二、OData 在asp.net mvc中的用法 1、在vs中新建webApi項目 2、添加測試類型 3、開啟EF自動遷移,添加EF上下文, 4.在數 ...
一、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(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查詢介面