Webapi Learning Note 07: Using the Webapi core file template--Creating an OData endpoint

Source: Internet
Author: User
Tags connectionstrings

1.Web Project

1.1 Overview

The EF access and operations database described above is out (of course not), and this chapter uses OData (open source data protocol) ...

1.2 Creating a Project

In Solution Explorer, right-click Add-New Solution folder named: OData

Right-click the "OData" Logical folder, add-"New project:

1.3 Installing the OData framework

1.4 Adding a model

Under the Models folder, add Product.cs, whose code:

namespaceproductservice.models{ Public classProduct { Public intId {Get;Set; }  Public stringName {Get;Set; }  Public decimalPrice {Get;Set; }  Public stringCategory {Get;Set; } }}

1.5 Installing EF

1.6 Adding a Context class

Under the Models folder, add EFContext.cs, whose code:

using System.Data.Entity; namespace productservice.models{    publicclass  efcontext:dbcontext    {          public efcontext ()            base("name=productcontext"         {        }        publicgetset;}}    }

1.7 Connection string

Under <configuration> in Web. config, add:

  <connectionStrings>    <add name="productcontext" connectionstring="          Initial catalog=productdb; Integrated security=true; multipleactiveresultsets=True;         AttachDbFileName=| datadirectory| Productdb.mdf"      providername="System.Data.SqlClient "/>  </connectionStrings>

1.8 Configuring Endpoints
Modify the App_start\webapiconfig.cs, its code:

usingProductservice.models;usingSystem.Web.Http;usingSystem.Web.OData.Builder;usingSystem.Web.OData.Extensions;namespaceproductservice{ Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Create an Entity Data Model (EDM)Odatamodelbuilder Builder =NewOdataconventionmodelbuilder (); Builder. EntitySet<Product> (" Products"); //Add RouteCONFIG. Mapodataserviceroute (routeName:"Odataroute", Routeprefix:NULL, Model:builder.            Getedmmodel ()); //Web API Routing//CONFIG.            Maphttpattributeroutes (); //CONFIG. Routes.maphttproute (//Name: "Defaultapi",//routetemplate: "Api/{controller}/{id}",//defaults:new {id = routeparameter.optional}//);        }    }}

1.9 Adding a Controller
Under the Controllers folder, add ProductsController.cs, whose code:

usingProductservice.models;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Linq;usingSystem.Net;usingSystem.Threading.Tasks;usingSystem.Web.Http;usingSystem.Web.OData;namespaceproductservice.controllers{ Public classProductscontroller:odatacontroller {Efcontext db =NewEfcontext (); [Enablequery] PublicIqueryable<product>Get () {returndb.        Products; } [Enablequery] PublicSingleresult<product> Get ([Fromodatauri]intkey) {IQueryable<Product> result = db. Products.where (p = p.id = =key); returnsingleresult.create (Result); }         Public AsyncTask<ihttpactionresult>Post (product product) {if(!modelstate.isvalid) {returnbadrequest (modelstate); } db.            Products.add (product); awaitdb.            Savechangesasync (); returnCreated (product); }         Public AsyncTask<ihttpactionresult> Patch ([Fromodatauri]intKey, delta<product>product) {            if(!modelstate.isvalid) {returnbadrequest (modelstate); }            varentity =awaitdb.            Products.findasync (key); if(Entity = =NULL)            {                returnNotFound (); } product.            Patch (entity); Try            {                awaitdb.            Savechangesasync (); }            Catch(dbupdateconcurrencyexception) {if(!productexists (Key)) {                    returnNotFound (); }                Else                {                    Throw; }            }            returnUpdated (entity); }         Public AsyncTask<ihttpactionresult> Put ([Fromodatauri]intkey, Product update) {            if(!modelstate.isvalid) {returnbadrequest (modelstate); }            if(Key! =Update. Id) {returnbadrequest (); } db. Entry (update). State=entitystate.modified; Try            {                awaitdb.            Savechangesasync (); }            Catch(dbupdateconcurrencyexception) {if(!productexists (Key)) {                    returnNotFound (); }                Else                {                    Throw; }            }            returnUpdated (update); }         Public AsyncTask<ihttpactionresult> Delete ([Fromodatauri]intkey) {            varProduct =awaitdb.            Products.findasync (key); if(Product = =NULL)            {                returnNotFound (); } db.            Products.remove (product); awaitdb.            Savechangesasync (); returnStatusCode (httpstatuscode.nocontent); }        Private BOOLProductexists (intkey) {            returnDb. Products.any (p = p.id = =key); }        protected Override voidDispose (BOOLdisposing) {db.            Dispose (); Base.        Dispose (disposing); }    }}

1.10 Run

Webapi Learning Note 07: Using the Webapi core file template--Creating an OData endpoint

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.