Asp. Net Web API 2 18th -- Working with Entity Relations in ODat

Source: Internet
Author: User

Before reading this article, you can go to the Asp. Net Web API 2 series navigation to view the sample code http://pan.baidu.com/s/1o6lqXN8 Most datasets define the relationship between entities: customers have orders, books have authors, and products have suppliers. The client can use OData to operate relations between entities. Given a product, you can find its suppliers. You can also create or delete a link. For example, you can set up a supplier for a product. This tutorial shows how to support these operations in Asp. Net Web APIs. The tutorial in this article is based on the tutorial in the previous section. http://www.cnblogs.com/aehyok/p/3545824.html . Add a Supplier Entity class first we need to Add a Supplier Entity class copy code namespace OData. models {public class Supplier {[Key] public string Key {get; set;} public string Name {get; set ;}}} the copy code class uses a string-type entity key. In practice, this may be less common than using an integer key. However, it is worth seeing how OData handles key types other than integers. Next, we will create a link by adding a Supplier attribute to the Product class. Copy the public class Product {public int ID {get; set;} public string Name {get; set;} public decimal Price {get; set;} public string Category {get; set ;}// New code [ForeignKey ("Supplier")] public string SupplierId {get; set ;}public virtual Supplier {get; set ;}} copy the code to add a new DbSet to the ProductServiceContext class so that the Entity Framework includes Supplier in the database table. Copy the public class ProductServiceContext: DbContext {public ProductServiceContext (): base ("name = ProductServiceContext") {} public DbSet <Product> Products {get; set ;} /// New Code public DbSet <Supplier> Suppliers {get; set ;}} copy the Code in WebApiConfig. cs, add an EDM model of the "Suppliers" entity: ODataConventionModelBuilder builder = new ODataConventionModelBuilder (); builder. entitySet <Product> ("Products"); // New cod E: builder. entitySet <Supplier> ("Suppliers"); Navigation Properties in order to Get a product Supplier, the client sends a GET request: Get/Products (1) /Supplier has a Supplier navigation attribute on the Product type. In this instance, Supplier is a single item. However, a navigation attribute can return a set (one-to-many or many-to-many relationship ). To support this request, add the following method to ProductsController: copy the code // GET/Products (1)/Supplier public Supplier GetSupplier ([FromODataUri] int key) {Product product = db. products. firstOrDefault (p => p. ID = key); if (product = null) {throw new HttpResponseException (HttpStatusCode. notFound);} return product. supplier;} copy the code key. This parameter is the key of this Product. This method returns the associated object-in this instance, it is a Supplier object. The method name and parameter name are very important. In short, if the navigation property is named as "X", you need to add a method named "GetX. This method must use a parameter named "key" to match the key of the parent data type. It is also important to have the [FromOdataUri] attribute on key parameters. When it parses the key from the requested URL, this property will tell the Web API to use the Odata syntax rules. Creating and Deleting LinksOData supports Creating and Deleting relationships between two entities. In OData terminology, this relationship is a "link ". Each link has a Url with entity/$ links/entity. For example, the link from the product to the Supplier looks like this:/Products (1)/$ links/Supplier in order to create a new link, the client sends a post request to the url uri. The request message body is the URI of the target object. For example, assume that the key of a supplier is "CTSO ". To create a link from "Product (1)" to "Supplier ('ctso')", the client sends a request as follows: POST http://localhost/odata/Products (1)/$ links/SupplierContent-Type: application/jsonContent-Length: 50 {"url ":" http://localhost/odata/Suppliers ('Ctso') "} the client sends a DELETE request to the url uri to DELETE a link. Creating Links to enable a client to create a product-supplier link, you need to add the following code in the ProductsController class: copy the Code [AcceptVerbs ("POST", "PUT")] public async Task <IHttpActionResult> CreateLink ([FromODataUri] int key, string navigationProperty, [FromBody] Uri link) {if (! ModelState. isValid) {return BadRequest (ModelState);} Product product = await db. products. findAsync (key); if (product = null) {return NotFound ();} switch (navigationProperty) {case "Supplier": string supplierKey = GetKeyFromLinkUri <string> (link ); supplier supplier = await db. suppliers. findAsync (supplierKey); if (supplier = null) {return NotFound ();} product. supplier = supplier; await db. sav EChangesAsync (); return StatusCode (HttpStatusCode. noContent); default: return NotFound () ;}} copy the Code. This method has three parameters: the first key is the key directed to the parent object, and the second navigationProperty: the name of the navigation attribute. For example, Supplier is the most suitable navigation attribute. Third link: The uri of the OData of the linked object. This value is obtained from the message body. For example, the url uri may be" http://localhost/odata/Suppliers ('Ctso') ", that is, the supplier has ID =" CTSO ". This method uses this link to find Supplier. If a matched Supplier is found, this method sets the Supplier attribute of the Product entity class and saves the result to the database. The most difficult part is parsing the link URI. Basically, you need to simulate sending a get request to that URI. The following helper method will show how to handle it. This method calls the Web API routing process and returns an OData object to display the converted OData path. For a link URI, this fragment number should contain an entity key. Copy the code // Helper method to extract the key from an OData link URI. private TKey GetKeyFromLinkUri <TKey> (Uri link) {TKey key = default (TKey); // Get the route that was used for this request. IHttpRoute route = Request. getRouteData (). route; // Create an equivalent self-hosted route. IHttpRoute newRoute = new HttpRoute (route. routeTemplate, new HttpRouteValueDictionary (route. defaults), new HttpRouteValueD Ictionary (route. constraints), new HttpRouteValueDictionary (route. dataTokens), route. handler); // Create a fake GET request for the link URI. var tmpRequest = new HttpRequestMessage (HttpMethod. get, link); // Send this request through the routing process. var routeData = newRoute. getRouteData (Request. getConfiguration (). virtualPathRoot, tmpRequest); // If the GET request matches the route, use the p Ath segments to find the key. if (routeData! = Null) {ODataPath path = tmpRequest. GetODataPath (); var segment = path. Segments. OfType <KeyValuePathSegment> (). FirstOrDefault (); if (segment! = Null) {// Convert the segment into the key type. key = (TKey) ODataUriUtils. convertFromUriLiteral (segment. value, ODataVersion. v3) ;}} return key ;}copy the code Deleting Links to delete a link, add the following code to the ProductsController class: copy the code public async Task <IHttpActionResult> DeleteLink ([FromODataUri] int key, string navigationProperty) {Product product = await db. products. findAsync (key); if (product = null) {return NotFound ();} Switch (navigationProperty) {case "Supplier": product. supplier = null; await db. saveChangesAsync (); return StatusCode (HttpStatusCode. noContent); default: return NotFound () ;}} in this example, this navigation property is a simple Supplier entity. If the navigation property is a set, the URI that deletes a link must have a key in the associated object. For example: DELETE/odata/Mers MERs (1)/$ links/Orders (1). Here we show an example of deleting one of the many-to-many relationships.

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.