標籤:style blog http io color ar os 使用 sp
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運行
WebApi學習筆記07:使用webapi核心檔案模板 --建立OData端點