在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本篇体验OData的Action和Function功能。上下文信息参考"ASP.NET Web API基于OData的增删改查,以及处理实体间关系"。在本文之前,我存在的疑惑包括:
● 为什么需要OData的Action和Function功能?
为某个Product添加Action
如果我们希望通过http://localhost:54714/odata/Products(1)/SomeActionName来实现在某个Product基础上,为Product的关联表ProductRating添加一条数据,该如何做到呢?
public class ProductRating { public int ID { get; set; } public int Rating { get; set; } public int ProductID { get; set; } public virtual Product Product { get; set; } }
把模型添加到上下文中:
public class ProductsContext : DbContext { public ProductsContext() : base("name=ProductsContext") { } public DbSet<Product> Products { get; set; } public DbSet<Supplier> Suppliers { get; set; } public DbSet<ProductRating> Ratings { get; set; } }
添加迁移并更新数据库:
ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.Namespace = "ProductService"; builder.EntitySet<Product>("Products");//创建EntityDataModel(EDM) builder.EntitySet<Supplier>("Suppliers"); //http://localhost/Products(1)/ProductService.Rate 注意需要在Web.config中添加配置,因为在IIS上不允许带点,否则会返回404 builder.EntityType<Product>() .Action("Rate")//给EDM添加一个Action .Parameter<int>("Rating"); //Rating作为参数在前后端传递 config.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: "odata", model:builder.GetEdmModel());
以上,
//这里的action名称Rate必须和EDM定义的时候保持一致 [HttpPost] public async Task<IHttpActionResult> Rate([FromODataUri] int key, ODataActionParameters parameters) { //先验证 if(!ModelState.IsValid) { return BadRequest(); } //再取值 int rating = (int)parameters["Rating"]; //实施操作 db.Ratings.Add(new ProductRating { ProductID = key, Rating = rating }); //捕获异常 try { await db.SaveChangesAsync(); } catch (DbUpdateException ex) { if (!ProductExists(key)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
可见,后端是通过ODataActionParameters来接受前端传来的变量Rating。
<system.webServer> <handlers> ... <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="/odata/*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>
重新请求,返回:204 No Content
为Product集合添加Action
如果想为Products集合添加如下方法发出如下请求:http://localhost:54714/odata/Products/ProductService.MostExpensive
builder.EntityType<Product>().Collection .Function("MostExpensive") .Returns<double>();
在ProductsController中添加如下Action:
[HttpGet] public IHttpActionResult MostExpensive() { var product = db.Products.Max(x => x.Price); return Ok(product); }
前端请求: builder.Function("GetSalesTaxRate") .Returns<double>() .Parameter<int>("PostalCode");
在某个Controller中添加如下:
[HttpGet] [ODataRoute("GetSalesTaxRate(PostalCode={postalCode})")] public IHttpActionResult GetSalesTaxRate([FromODataUri] int postalCode) { double rate = 5.8; return Ok(rate); }
以上,ODataRoute设定路由规则。前端发出如下请求:
|
请发表评论