Standardized open source data protocol for program database format in order to enhance data compatibility between various Web applications, Microsoft launched an open source data Protocol (OData) program designed to promote standardization of Web application database formats, and at the same time released a development tool for the OData protocol. To facilitate the use of Web-based program developers. Open Data Protocol is a Web protocol used to query and update data, providing a way to expose the data that exists in the application. OData is used and built on many web technologies, such as HTTP, Atom publishing Protocol (AtomPub), and JSON, providing the ability to access information from a variety of applications, services, and repositories. OData is used to expose and access information from a variety of data sources, including but not limited to: relational databases, file systems, content management systems, and traditional web sites. Create a project
Create a new ASP. NET Web application project in VS, named "Personsservice", such as:
Installing the Nuet package
Search Microsoft.AspNet.Odata Package with EntityFramework package installation
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:
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;}} }
Build Database
Open the Web. config file and add the following connectionstrings node to the configuration element:
<connectionStrings> <add name= "Personscontext" connectionstring= "server=.;D atabase=personsdb;integrated security=true "providername=" System.Data.SqlClient "/> </ Connectionstrings>
Under the Models folder, add a Personscontext class:
Using System.data.entity;namespace personsservice.models{public class Personscontext:dbcontext { Public Personscontext () : Base ("Name=personscontext") { } public dbset<person> Persons {get; Set } }}
Open NuGet Package Manager, Package Manager console Enter the following command "Enable-migrations", "Add-migration", "Update-database"
This is the time to open SQL Server and see the database that has been created.
Configuring the OData endpoint
Open the App_start/webapiconfig.cs file and configure the following new code
Using microsoft.odata.edm;using personsservice.models;using system.web.http;using system.web.odata.builder;using System.web.odata.extensions;namespace personsservice{public static class Webapiconfig {public static void R Egister (httpconfiguration config) {//Web API Configuration and services//Web API routing config. Maphttpattributeroutes (); Config. Routes.maphttproute (Name: "Defaultapi", Routetemplate: "Api/{controller}/{id}", defaults:new {id = routeparameter.optional}); Build the Routing service config. Mapodataserviceroute (routeName: "OData", Routeprefix: "OData", Model:getmod El ()); } private static Iedmmodel Getmodel () {var builder = new Odataconventionmodelbuilder (); var Esperson = Builder. Entityset<person> ("Persons"); Return 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:
Modify the controller code as follows:
Using personsservice.models;using system.linq;using system.web.odata;namespace personsservice.controllers{ public class Personscontroller:odatacontroller { private readonly personscontext db = new Personscontext ();
[enablequery] public iqueryable<person> Get () { return db. Persons; } [Enablequery] Public iqueryable<person> Get ([fromodatauri] int key) { return db. Persons.where (r=> r.id==key);}}
At this point we manually add some data to the database,
Well, now we're running the project trying to request the next
Request Http://localhost:3370/odata/Persons
Now that the data is out, try requesting a single person
Http://localhost:3370/odata/Persons (1)
Everything's fine.
The parameterless Get () method returns a collection of the entire person table.
The Get ([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.
Add a Post method to add person
[HttpPost] Public Ihttpactionresult Post (man person) { if (! Modelstate.isvalid) { return badrequest (modelstate); } Db. Persons.add (person); Db. SaveChanges (); return Created (person); }
Using the POST request Http://localhost:3370/odata/Persons
Look at the database Zhao Liu has been added, now add a modification method
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.
[Acceptverbs ("PATCH", "MERGE")] Public Ihttpactionresult patch ([fromodatauri] int key, delta<person> patch) { 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) { 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); }
Subsequent additions to the OData configuration for custom routing issues.
Odata Custom Route
[Enablequery, HttpGet] [Odataroute ("Products ({ID})/default.getcatandtown")] Public Ihttpactionresult Getcatandtown ([fromodatauri] int id) { var list = db. Products.where (r = r.id = = Id); return Ok (list); }
Of course this time we request http://localhost:6785//Odata/Products (1)/default.getcatandtown will error 404, the solution is to add a trailing slash to the requested URL
This time we http://localhost:6785//Odata/Products (1)/default.getcatandtown/will be good, the specific reason is unknown. or modify the Web. config file
<system.webServer>
ASP. NET Web API 2 OData v4 Tutorial