1.Web项目
1.1概述
前面介绍的EF访问和操作数据库,要OUT了(当然不是啦),这章使用OData(开源数据协议)……
1.2创建项目
在“解决方案资源管理器”中右键,添加-》新建解决方案文件夹,命名为:OData
右键“OData”逻辑文件夹,添加-》新建项目:
1.3安装OData框架
1.4添加模型
在Models文件夹下,添加Product.cs,其代码:
namespace ProductService.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } } }
1.5安装EF
1.6添加上下文类
在Models文件夹下,添加EFContext.cs,其代码:
using System.Data.Entity; namespace ProductService.Models { public class EFContext : DbContext { public EFContext() : base("name=ProductContext") { } public DbSet<Product> Products { get; set; } } }
1.7连接字符串
在Web.config里<configuration>下,添加:
<connectionStrings> <add name="ProductContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=ProductDB; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ProductDB.mdf" providerName="System.Data.SqlClient" /> </connectionStrings>
1.8配置端点
修改App_Start\WebApiConfig.cs,其代码:
using ProductService.Models; using System.Web.Http; using System.Web.OData.Builder; using System.Web.OData.Extensions; namespace ProductService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 //创建实体数据模型 (EDM) ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Product>("Products"); //添加路由 config.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: null, model: builder.GetEdmModel()); // Web API 路由 //config.MapHttpAttributeRoutes(); //config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "api/{controller}/{id}", // defaults: new { id = RouteParameter.Optional } //); } } }
1.9添加控制器
在Controllers文件夹下,添加ProductsController.cs,其代码:
using ProductService.Models; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using System.Web.OData; namespace ProductService.Controllers { public class ProductsController : ODataController { EFContext db = new EFContext(); [EnableQuery] public IQueryable<Product> Get() { return db.Products; } [EnableQuery] public SingleResult<Product> Get([FromODataUri] int key) { IQueryable<Product> result = db.Products.Where(p => p.Id == key); return SingleResult.Create(result); } public async Task<IHttpActionResult> Post(Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Products.Add(product); await db.SaveChangesAsync(); return Created(product); } public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var entity = await db.Products.FindAsync(key); if (entity == null) { return NotFound(); } product.Patch(entity); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(key)) { return NotFound(); } else { throw; } } return Updated(entity); } public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (key != update.Id) { return BadRequest(); } db.Entry(update).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(key)) { return NotFound(); } else { throw; } } return Updated(update); } public async Task<IHttpActionResult> Delete([FromODataUri] int key) { var product = await db.Products.FindAsync(key); if (product == null) { return NotFound(); } db.Products.Remove(product); await db.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } private bool ProductExists(int key) { return db.Products.Any(p => p.Id == key); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
1.10运行
时间: 2024-10-18 20:51:08