"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Entity Relations in OData v4 Using ASP.NET Web API 2.2

by Mike Wasson

Most data sets define relations between entities: Customers have orders; books have authors; products have suppliers. Using OData, clients can navigate over entity relations. Given a product, you can find the supplier. You can also create or remove relationships. For example, you can set the supplier for a product.

This tutorial shows how to support these operations in OData v4 using ASP.NET Web API. The tutorial builds on the tutorial Create an OData v4 Endpoint Using ASP.NET Web API 2.

Software versions used in the tutorial

Tutorial versions

For the OData Version 3, see Supporting Entity Relations in OData v3.

Add a Supplier Entity

[!NOTE] The tutorial builds on the tutorial Create an OData v4 Endpoint Using ASP.NET Web API 2.

First, we need a related entity. Add a class named Supplier in the Models folder.

[!code-csharpMain]

   1:  using System.Collections.Generic;
   2:   
   3:  namespace ProductService.Models
   4:  {
   5:      public class Supplier
   6:      {
   7:          public int Id { get; set; }
   8:          public string Name { get; set; }
   9:   
  10:          public ICollection<Product> Products { get; set; }
  11:      }
  12:  }

Add a navigation property to the Product class:

[!code-csharpMain]

   1:  using System.ComponentModel.DataAnnotations.Schema;
   2:   
   3:  namespace ProductService.Models
   4:  {
   5:      public class Product
   6:      {
   7:          public int Id { get; set; }
   8:          public string Name { get; set; }
   9:          public decimal Price { get; set; }
  10:          public string Category { get; set; }
  11:   
  12:          // New code:    
  13:          [ForeignKey("Supplier")]
  14:          public int? SupplierId { get; set; }
  15:          public virtual Supplier Supplier { get; set; }
  16:      }
  17:  }

Add a new DbSet to the ProductsContext class, so that Entity Framework will include the Supplier table in the database.

[!code-csharpMain]

   1:  public class ProductsContext : DbContext
   2:  {
   3:      static ProductsContext()
   4:      {
   5:          Database.SetInitializer(new ProductInitializer());
   6:      }
   7:   
   8:      public DbSet<Product> Products { get; set; }
   9:      // New code:
  10:      public DbSet<Supplier> Suppliers { get; set; }
  11:  }

In WebApiConfig.cs, add a “Suppliers” entity set to the entity data model:

[!code-csharpMain]

   1:  public static void Register(HttpConfiguration config)
   2:  {
   3:      ODataModelBuilder builder = new ODataConventionModelBuilder();
   4:      builder.EntitySet<Product>("Products");
   5:      // New code:
   6:      builder.EntitySet<Supplier>("Suppliers");
   7:      config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
   8:  }

Add a Suppliers Controller

Add a SuppliersController class to the Controllers folder.

[!code-csharpMain]

   1:  using ProductService.Models;
   2:  using System.Linq;
   3:  using System.Web.OData;
   4:   
   5:  namespace ProductService.Controllers
   6:  {
   7:      public class SuppliersController : ODataController
   8:      {
   9:          ProductsContext db = new ProductsContext();
  10:   
  11:          protected override void Dispose(bool disposing)
  12:          {
  13:              db.Dispose();
  14:              base.Dispose(disposing);
  15:          }
  16:      }
  17:  }

I won’t show how to add CRUD operations for this controller. The steps are the same as for the Products controller (see Create an OData v4 Endpoint).

To get the supplier for a product, the client sends a GET request:

[!code-consoleMain]

   1:  GET /Products(1)/Supplier

To support this request, add the following method to the ProductsController class:

[!code-csharpMain]

   1:  public class ProductsController : ODataController
   2:  {
   3:      // GET /Products(1)/Supplier
   4:      [EnableQuery]
   5:      public SingleResult<Supplier> GetSupplier([FromODataUri] int key)
   6:      {
   7:          var result = db.Products.Where(m => m.Id == key).Select(m => m.Supplier);
   8:          return SingleResult.Create(result);
   9:      }
  10:   
  11:     // Other controller methods not shown.
  12:  }

This method uses a default naming convention

If you follow this naming convention, Web API automatically maps the HTTP request to the controller method.

Example HTTP request:

[!code-consoleMain]

   1:  GET http://myproductservice.example.com/Products(1)/Supplier HTTP/1.1
   2:  User-Agent: Fiddler
   3:  Host: myproductservice.example.com

Example HTTP response:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Length: 125
   3:  Content-Type: application/json; odata.metadata=minimal; odata.streaming=true
   4:  Server: Microsoft-IIS/8.0
   5:  OData-Version: 4.0
   6:  Date: Tue, 08 Jul 2014 00:44:27 GMT
   7:   
   8:  {
   9:    "@odata.context":"http://myproductservice.example.com/$metadata#Suppliers/$entity","Id":2,"Name":"Wingtip Toys"
  10:  }

In the previous example, a product has one supplier. A navigation property can also return a collection. The following code gets the products for a supplier:

[!code-csharpMain]

   1:  public class SuppliersController : ODataController
   2:  {
   3:      // GET /Suppliers(1)/Products
   4:      [EnableQuery]
   5:      public IQueryable<Product> GetProducts([FromODataUri] int key)
   6:      {
   7:          return db.Suppliers.Where(m => m.Id.Equals(key)).SelectMany(m => m.Products);
   8:      }
   9:   
  10:      // Other controller methods not shown.
  11:  }

In this case, the method returns an IQueryable instead of a SingleResult<T>

Example HTTP request:

[!code-consoleMain]

   1:  GET http://myproductservice.example.com/Suppliers(2)/Products HTTP/1.1
   2:  User-Agent: Fiddler
   3:  Host: myproductservice.example.com

Example HTTP response:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Length: 372
   3:  Content-Type: application/json; odata.metadata=minimal; odata.streaming=true
   4:  Server: Microsoft-IIS/8.0
   5:  OData-Version: 4.0
   6:  Date: Tue, 08 Jul 2014 01:06:54 GMT
   7:   
   8:  {
   9:    "@odata.context":"http://myproductservice.example.com/$metadata#Products","value":[
  10:      {
  11:        "Id":1,"Name":"Hat","Price":14.95,"Category":"Clothing","SupplierId":2
  12:      },{
  13:        "Id":2,"Name":"Socks","Price":6.95,"Category":"Clothing","SupplierId":2
  14:      },{
  15:        "Id":4,"Name":"Pogo Stick","Price":29.99,"Category":"Toys","SupplierId":2
  16:      }
  17:    ]
  18:  }

Creating a Relationship Between Entities

OData supports creating or removing relationships between two existing entities. In OData v4 terminology, the relationship is a “reference”. (In OData v3, the relationship was called a link. The protocol differences don’t matter for this tutorial.)

A reference has its own URI, with the form /Entity/NavigationProperty/$ref. For example, here is the URI to address the reference between a product and its supplier:

[!code-consoleMain]

   1:  http:/host/Products(1)/Supplier/$ref

To add a relationship, the client sends a POST or PUT request to this address.

The body of the request contains the URI of the other entity in the relation. Here is an example request:

[!code-consoleMain]

   1:  PUT http://myproductservice.example.com/Products(6)/Supplier/$ref HTTP/1.1
   2:  OData-Version: 4.0;NetFx
   3:  OData-MaxVersion: 4.0;NetFx
   4:  Accept: application/json;odata.metadata=minimal
   5:  Accept-Charset: UTF-8
   6:  Content-Type: application/json;odata.metadata=minimal
   7:  User-Agent: Microsoft ADO.NET Data Services
   8:  Host: myproductservice.example.com
   9:  Content-Length: 70
  10:  Expect: 100-continue
  11:   
  12:  {"@odata.id":"http://myproductservice.example.com/Suppliers(4)"}

In this example, the client sends a PUT request to /Products(6)/Supplier/$ref, which is the $ref URI for the Supplier of the product with ID = 6. If the request succeeds, the server sends a 204 (No Content) response:

[!code-consoleMain]

   1:  HTTP/1.1 204 No Content
   2:  Server: Microsoft-IIS/8.0
   3:  Date: Tue, 08 Jul 2014 06:35:59 GMT

Here is the controller method to add a relationship to a Product:

[!code-csharpMain]

   1:  public class ProductsController : ODataController
   2:  {
   3:      [AcceptVerbs("POST", "PUT")]
   4:      public async Task<IHttpActionResult> CreateRef([FromODataUri] int key, 
   5:          string navigationProperty, [FromBody] Uri link)
   6:      {
   7:          var product = await db.Products.SingleOrDefaultAsync(p => p.Id == key);
   8:          if (product == null)
   9:          {
  10:              return NotFound();
  11:          }
  12:          switch (navigationProperty)
  13:          {
  14:              case "Supplier":
  15:                  // Note: The code for GetKeyFromUri is shown later in this topic.
  16:                  var relatedKey = Helpers.GetKeyFromUri<int>(Request, link);
  17:                  var supplier = await db.Suppliers.SingleOrDefaultAsync(f => f.Id == relatedKey);
  18:                  if (supplier == null)
  19:                  {
  20:                      return NotFound();
  21:                  }
  22:   
  23:                  product.Supplier = supplier;
  24:                  break;
  25:   
  26:              default:
  27:                  return StatusCode(HttpStatusCode.NotImplemented);
  28:          }
  29:          await db.SaveChangesAsync();
  30:          return StatusCode(HttpStatusCode.NoContent);
  31:      }
  32:   
  33:      // Other controller methods not shown.
  34:  }

The navigationProperty parameter specifies which relationship to set. (If there is more than one navigation property on the entity, you can add more case statements.)

The link parameter contains the URI of the supplier. Web API automatically parses the request body to get the value for this parameter.

To look up the supplier, we need the ID (or key), which is part of the link parameter. To do this, use the following helper method:

[!code-csharpMain]

   1:  using Microsoft.OData.Core;
   2:  using Microsoft.OData.Core.UriParser;
   3:  using System;
   4:  using System.Collections.Generic;
   5:  using System.Linq;
   6:  using System.Net.Http;
   7:  using System.Web.Http.Routing;
   8:  using System.Web.OData.Extensions;
   9:  using System.Web.OData.Routing;
  10:   
  11:  namespace ProductService
  12:  {
  13:      public static class Helpers
  14:      {
  15:          public static TKey GetKeyFromUri<TKey>(HttpRequestMessage request, Uri uri)
  16:          {
  17:              if (uri == null)
  18:              {
  19:                  throw new ArgumentNullException("uri");
  20:              }
  21:   
  22:              var urlHelper = request.GetUrlHelper() ?? new UrlHelper(request);
  23:   
  24:              string serviceRoot = urlHelper.CreateODataLink(
  25:                  request.ODataProperties().RouteName, 
  26:                  request.ODataProperties().PathHandler, new List<ODataPathSegment>());
  27:              var odataPath = request.ODataProperties().PathHandler.Parse(
  28:                  request.ODataProperties().Model, 
  29:                  serviceRoot, uri.LocalPath);
  30:   
  31:              var keySegment = odataPath.Segments.OfType<KeyValuePathSegment>().FirstOrDefault();
  32:              if (keySegment == null)
  33:              {
  34:                  throw new InvalidOperationException("The link does not contain a key.");
  35:              }
  36:   
  37:              var value = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value, ODataVersion.V4);
  38:              return (TKey)value;
  39:          }
  40:   
  41:      }
  42:  }

Basically, this method uses the OData library to split the URI path into segments, find the segment that contains the key, and convert the key into the correct type.

Deleting a Relationship Between Entities

To delete a relationship, the client sends an HTTP DELETE request to the $ref URI:

[!code-consoleMain]

   1:  DELETE http://host/Products(1)/Supplier/$ref

Here is the controller method to delete the relationship between a Product and a Supplier:

[!code-csharpMain]

   1:  public class ProductsController : ODataController
   2:  {
   3:      public async Task<IHttpActionResult> DeleteRef([FromODataUri] int key, 
   4:          string navigationProperty, [FromBody] Uri link)
   5:      {
   6:          var product = db.Products.SingleOrDefault(p => p.Id == key);
   7:          if (product == null)
   8:          {
   9:              return NotFound();
  10:          }
  11:   
  12:          switch (navigationProperty)
  13:          {
  14:              case "Supplier":
  15:                  product.Supplier = null;
  16:                  break;
  17:   
  18:              default:
  19:                  return StatusCode(HttpStatusCode.NotImplemented);
  20:          }
  21:          await db.SaveChangesAsync();
  22:   
  23:          return StatusCode(HttpStatusCode.NoContent);
  24:      }        
  25:   
  26:      // Other controller methods not shown.
  27:  }

In this case, Product.Supplier is the “1” end of a 1-to-many relation, so you can remove the relationship just by setting Product.Supplier to null.

In the “many” end of a relationship, the client must specify which related entity to remove. To do so, the client sends the URI of the related entity in the query string of the request. For example, to remove “Product 1” from “Supplier 1”:

[!code-consoleMain]

   1:  DELETE http://host/Suppliers(1)/Products/$ref?$id=http://host/Products(1)

To support this in Web API, we need to include an extra parameter in the DeleteRef method. Here is the controller method to remove a product from the Supplier.Products relation.

[!code-csharpMain]

   1:  public class SuppliersController : ODataController
   2:  {
   3:      public async Task<IHttpActionResult> DeleteRef([FromODataUri] int key, 
   4:          [FromODataUri] string relatedKey, string navigationProperty)
   5:      {
   6:          var supplier = await db.Suppliers.SingleOrDefaultAsync(p => p.Id == key);
   7:          if (supplier == null)
   8:          {
   9:              return StatusCode(HttpStatusCode.NotFound);
  10:          }
  11:   
  12:          switch (navigationProperty)
  13:          {
  14:              case "Products":
  15:                  var productId = Convert.ToInt32(relatedKey);
  16:                  var product = await db.Products.SingleOrDefaultAsync(p => p.Id == productId);
  17:   
  18:                  if (product == null)
  19:                  {
  20:                      return NotFound();
  21:                  }
  22:                  product.Supplier = null;
  23:                  break;
  24:              default:
  25:                  return StatusCode(HttpStatusCode.NotImplemented);
  26:   
  27:          }
  28:          await db.SaveChangesAsync();
  29:   
  30:          return StatusCode(HttpStatusCode.NoContent);
  31:      }
  32:   
  33:      // Other controller methods not shown.
  34:  }

The key parameter is the key for the supplier, and the relatedKey parameter is the key for the product to remove from the Products relationship. Note that Web API automatically gets the key from the query string.



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4.htm
< THANKS ME>