[Go] Create an OData v4 endpoint with ASP. NET Web API 2

Source: Internet
Author: User
Tags connectionstrings

This article transferred from: http://www.cnblogs.com/farb/p/ODataAspNetWebAPI.html

Open Data Protocol ("OData") is a data access protocol for the web. OData provides a uniform way to perform CRUD operations on Datasets (Create,read,update,delete).
The ASP. NET Web API supports the V3 and V4 versions of the protocol, and can even create a V4 endpoint that runs side by end with the V3 endpoint.
This blog post demonstrates how to create an OData v4 endpoint that supports CRUD operations.

Software version used
    • Web API 2
    • OData V4
    • VS Update 5
    • EF6
    • . Net 4.5.2
Create vs Project

Create a new ASP. NET Web application project in VS, named "Personsservice", such as:

Then continue to look at:

Install the OData nuget package

Open the NuGet Package Manager console and enter the following command:

Install-Package Microsoft.AspNet.Odata

This command installs the latest version of the OData Nuget package.

Add Model Class

The model class is an object that represents the data entity in the app.

In Solution Explorer, under the Models folder, create a person class:

By convention, the model class should be placed under the Models folder, but you may not do so in your own project.

Here is the code for my person class:

namespace PersonsService.Models{    public class Person { public int Id { get; set; } public string Name { get; set; } public bool Gender { get; set; } public string UserName { get; set; } }}
Enable entity Framework

In this blog, we use the Code First mode of EF to create a database.

The Web API OData does not require that it must be EF. As long as the data access layer can convert database entities into model, any data access layer can be used.

First, install the NuGet package for EF. Use the following command in the Package Manager console:

Install-Package EntityFramework

Open the Web. config file and add the following connectionstrings node to the configuration element:

  <connectionStrings>    <add name="PersonsContext" connectionString="Server=.;Database=PersonsDB;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings>

Next, add a Personscontext class under the Models folder:

using System.Data.Entity;namespace PersonsService.Models{    public class PersonsContext:DbContext { public PersonsContext() : base("name=PersonsContext") { } public DbSet<Person> Persons { get; set; } }}

In the constructor, the "name=PersonsContext" name of the connection string is specified.

Configuring the OData Endpoint

Open the App_start/webapiconfig.cs file and configure the following new code (to remove the autogenerated code):

Using System.Web.Http;Using System.Web.OData.Builder;Using System.Web.OData.Extensions;using Personsservice.models; namespace personsservice{ public static class Webapiconfig { public static void C11>register (httpconfiguration config) { //new code Odatamodelbuilder builder= Odataconventionmodelbuilder (); Builder. Entityset<person> ("Persons"); config. Mapodataserviceroute (routeName:"OData", Routeprefix:"OData", Model:builder. Getedmmodel ()); } }}

The above code does two things:

    • Created an Entity Data Model ("entity", "short EDM").
    • A route was added.

The EDM is an abstract data model. The EDM is used to create a service metadata document. The Odataconventionmodelbuilder class creates an EDM using the default naming convention. This way requires the least amount of code to write. If you want to control the EDM more, you can use the Odatamodelbuilder class to create an EDM class that explicitly adds properties, keys, and navigation properties.

Routing tells the Web API how to route HTTP requests to endpoints. Call the mapodataserviceroute extension method to create an OData v4 route.

If your app has multiple OData endpoints, create a separate route for each endpoint, giving each route a unique route name and prefix (prefix).

Add an OData controller

A controller is a class that handles HTTP requests. In an OData app, you should create a separate controller for each entity set. And in this blog, we just have to create a controller for the person entity.

Under the Controllers folder, add a controller, as follows:

Right-click on the Controllers folder to add the controller, then select the selection, as there is no scaffolding for the OData v4.

The default has helped us generate the following code, basically we do not need to do anything, crud all have, hehe:

Using System.Data.Entity.Infrastructure;Using System.Linq;Using System.Net;Using System.Web.Http;Using System.Web.Http.ModelBinding;Using System.Web.OData;Using Personsservice.models;Namespacepersonsservice.controllers{/* Before adding a route to this controller, the Webapiconfig class may require you to make additional changes. Please merge these statements appropriately into the Register method of the Webapiconfig class. Note that the OData URL is case sensitive. Using System.Web.Http.OData.Builder; Using System.Web.Http.OData.Extensions; Using Personsservice.models; Odataconventionmodelbuilder builder = new Odataconventionmodelbuilder (); Builder. Entityset<person> ("Persons"); Config. Routes.mapodataserviceroute ("OData", "OData", builder.) Getedmmodel ()); */PublicClassPersonscontroller:Odatacontroller {Private Personscontext db =New Personscontext ();get:odata/persons [Enablequery]Public iqueryable<person>Getpersons () {Return DB. Persons; }Get:odata/persons (5) [Enablequery]Public singleresult<person>Getperson ([Fromodatauri]int key) {Return Singleresult.create (db. Persons.where (person = person). Id = = key); }Put:odata/persons (5)Public IhttpactionresultPut ([Fromodatauri]int key, delta<person> patch) {Validate (patch. GetEntity ());if (! Modelstate.isvalid) {Return Badrequest (modelstate); } Person person = db. Persons.find (key);if (person = =NULL) {return NotFound (); } patch. Put (person);try {db. SaveChanges (); }catch (dbupdateconcurrencyexception) {if (! Personexists (key)) {return NotFound (); }else {Throw } }return Updated (person); }Post:odata/personsPublic IhttpactionresultPost (Person person) {if (! Modelstate.isvalid) {Return Badrequest (modelstate); } db. Persons.add (person); Db. SaveChanges ();return Created (person); }Patch:odata/persons (5) [Acceptverbs ("PATCH","MERGE")]Public IhttpactionresultPatch ([Fromodatauri]int key, delta<person> patch) {Validate (patch. GetEntity ());if (! Modelstate.isvalid) {Return Badrequest (modelstate); } Person person = db. Persons.find (key);if (person = =NULL) {return NotFound (); } patch. Patch (person);try {db. SaveChanges (); }catch (dbupdateconcurrencyexception) {if (! Personexists (key)) {return NotFound (); }else {Throw } }return Updated (person); }Delete:odata/persons (5)Public IhttpactionresultDelete ([Fromodatauri]int key) {Person person = db. Persons.find (key);if (person = =null) {return NotFound ();} db. Persons.remove (person); Db. SaveChanges (); return StatusCode (httpstatuscode.nocontent);} protected override void dispose (bool disposing) {if (disposing) {db. Dispose (); } base. Dispose (disposing); } private bool personexists (int key) { return db. Persons.count (E = e.id = = key) > 0;}}}        

The controller uses the EF to access the database using the Personscontext class. Note the controller overrides the Dispose method to release Personscontext.

Build Database

Generate the database from the migration of code first and populate the data. It's not the focus of this section on how to use Codefirst to build a database, so here's a stroke. The following is the data that I generated for the database that has been populated:

Querying entity Sets

The automatically generated query operations are as follows:

// GET: odata/Persons        [EnableQuery]        public IQueryable<Person> GetPersons() { return db.Persons; } // GET: odata/Persons(5) [EnableQuery] public SingleResult<Person> GetPerson([FromODataUri] int key) { return SingleResult.Create(db.Persons.Where(person => person.Id == key)); }

The Getpersons () method with no parameters returns a collection of the entire person table.
The Getperson ([Fromodatauri] int key) method returns the person of the specified ID.

The [enablequery] attribute allows clients to modify queries using query options such as $filter, $sort, and $page.

Operation Demo

New entity

Allow the client to add a new person entity to the database:

// POST: odata/Persons        public IHttpActionResult Post(Person person) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Persons.Add(person); db.SaveChanges(); return Created(person); }
Update entity

OData supports two different semantic update entities, including patches and put.

    • Patch performs a partial update, and the client recognizes only the properties to be updated.
    • Put replaces the entire entity.

The disadvantage of put is that the client must send all attributes of the entity, including values that have not changed.
The OData specification states that patches are preferred.

The following is the generated code:

Patch:odata/persons (5) [Acceptverbs ("PATCH","MERGE")]public ihttpactionresult patch ([ Fromodatauri] int key, Delta<person> patch) {Validate (patch. GetEntity ()); if (! Modelstate.isvalid) {return badrequest (modelstate);} Person person = db. Persons.find (key); if (person = = null) {return NotFound (); } patch. Patch (person); try {db. SaveChanges (); } catch (dbupdateconcurrencyexception) {if (! Personexists (key)) {return NotFound ();} else {throw;}} return Updated (person);}          

In patch, the controller uses the Delta type to track changes.

Delete Entity

Allow clients to delete a person from the database:

// DELETE: odata/Persons(5)        public IHttpActionResult Delete([FromODataUri] int key) { Person person = db.Persons.Find(key); if (person == null) { return NotFound(); } db.Persons.Remove(person); db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); }
Good text to the top

[Go] Create an OData v4 endpoint with ASP. NET Web API 2

Related Article

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.