Supporting Entity Relations in OData v3 with Web API 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 ASP.NET Web API. The tutorial builds on the tutorial Creating an OData v3 Endpoint with Web API 2.
Software versions used in the tutorial
- Web API 2
- OData Version 3
- Entity Framework 6
Add a Supplier Entity
First we need to add a new entity type to our OData feed. We’ll add a Supplier
class.
[!code-csharpMain]
1: using System.ComponentModel.DataAnnotations;
2:
3: namespace ProductService.Models
4: {
5: public class Supplier
6: {
7: [Key]
8: public string Key { get; set; }
9: public string Name { get; set; }
10: }
11: }
This class uses a string for the entity key. In practice, that might be less common than using an integer key. But it’s worth seeing how OData handles other key types besides integers.
Next, we’ll create a relation by adding a Supplier
property to the Product
class:
[!code-csharpMain]
1: public class Product
2: {
3: public int ID { get; set; }
4: public string Name { get; set; }
5: public decimal Price { get; set; }
6: public string Category { get; set; }
7:
8: // New code
9: [ForeignKey("Supplier")]
10: public string SupplierId { get; set; }
11: public virtual Supplier Supplier { get; set; }
12: }
Add a new DbSet to the ProductServiceContext
class, so that Entity Framework will include the Supplier
table in the database.
[!code-csharpMain]
1: public class ProductServiceContext : DbContext
2: {
3: public ProductServiceContext() : base("name=ProductServiceContext")
4: {
5: }
6:
7: public System.Data.Entity.DbSet<ProductService.Models.Product> Products { get; set; }
8: // New code:
9: public System.Data.Entity.DbSet<ProductService.Models.Supplier> Suppliers { get; set; }
10: }
In WebApiConfig.cs, add a “Suppliers” entity to the EDM model:
[!code-csharpMain]
1: ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
2: builder.EntitySet<Product>("Products");
3: // New code:
4: builder.EntitySet<Supplier>("Suppliers");
Navigation Properties
To get the supplier for a product, the client sends a GET request:
[!code-consoleMain]
1: GET /Products(1)/Supplier
Here “Supplier” is a navigation property on the Product
type. In this case, Supplier
refers to a single item, but a navigation property can also return a collection (one-to-many or many-to-many relation).
To support this request, add the following method to the ProductsController
class:
[!code-csharpMain]
1: // GET /Products(1)/Supplier
2: public Supplier GetSupplier([FromODataUri] int key)
3: {
4: Product product = _context.Products.FirstOrDefault(p => p.ID == key);
5: if (product == null)
6: {
7: throw new HttpResponseException(HttpStatusCode.NotFound);
8: }
9: return product.Supplier;
10: }
The key parameter is the key of the product. The method returns the related entity—in this case, a Supplier
instance. The method name and parameter name are both important. In general, if the navigation property is named “X”, you need to add a method named “GetX”. The method must take a parameter named “key” that matches the data type of the parent’s key.
It is also important to include the [FromOdataUri] attribute in the key parameter. This attribute tells Web API to use OData syntax rules when it parses the key from the request URI.
Creating and Deleting Links
OData supports creating or removing relationships between two entities. In OData terminology, the relationship is a “link.” Each link has a URI with the form entity/$links/entity. For example, the link from product to supplier looks like this:
[!code-consoleMain]
1: /Products(1)/$links/Supplier
To create a new link, the client sends a POST request to the link URI. The body of the request is the URI of the target entity. For example, suppose there is a supplier with the key “CTSO”. To create a link from “Product(1)” to “Supplier(‘CTSO’)”, the client sends a request like the following:
[!code-consoleMain]
1: POST http://localhost/odata/Products(1)/$links/Supplier
2: Content-Type: application/json
3: Content-Length: 50
4:
5: {"url":"http://localhost/odata/Suppliers('CTSO')"}
To delete a link, the client sends a DELETE request to the link URI.
Creating Links
To enable a client to create product-supplier links, add the following code to the ProductsController
class:
[!code-csharpMain]
1: [AcceptVerbs("POST", "PUT")]
2: public async Task<IHttpActionResult> CreateLink([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
3: {
4: if (!ModelState.IsValid)
5: {
6: return BadRequest(ModelState);
7: }
8:
9: Product product = await db.Products.FindAsync(key);
10: if (product == null)
11: {
12: return NotFound();
13: }
14:
15: switch (navigationProperty)
16: {
17: case "Supplier":
18: string supplierKey = GetKeyFromLinkUri<string>(link);
19: Supplier supplier = await db.Suppliers.FindAsync(supplierKey);
20: if (supplier == null)
21: {
22: return NotFound();
23: }
24: product.Supplier = supplier;
25: await db.SaveChangesAsync();
26: return StatusCode(HttpStatusCode.NoContent);
27:
28: default:
29: return NotFound();
30: }
31: }
This method takes three parameters:
- key: The key to the parent entity (the product)
- navigationProperty: The name of the navigation property. In this example, the only valid navigation property is “Supplier”.
- link: The OData URI of the related entity. This value is taken from the request body. For example, the link URI might be “
http://localhost/odata/Suppliers('CTSO')
, meaning the supplier with ID = ‘CTSO’.
The method uses the link to look up the supplier. If the matching supplier is found, the method sets the Product.Supplier
property and saves the result to the database.
The hardest part is parsing the link URI. Basically, you need to simulate the result of sending a GET request to that URI. The following helper method shows how to do this. The method invokes the Web API routing process and gets back an ODataPath instance that represents the parsed OData path. For a link URI, one of the segments should be the entity key. (If not, the client sent a bad URI.)
[!code-csharpMain]
1: // Helper method to extract the key from an OData link URI.
2: private TKey GetKeyFromLinkUri<TKey>(Uri link)
3: {
4: TKey key = default(TKey);
5:
6: // Get the route that was used for this request.
7: IHttpRoute route = Request.GetRouteData().Route;
8:
9: // Create an equivalent self-hosted route.
10: IHttpRoute newRoute = new HttpRoute(route.RouteTemplate,
11: new HttpRouteValueDictionary(route.Defaults),
12: new HttpRouteValueDictionary(route.Constraints),
13: new HttpRouteValueDictionary(route.DataTokens), route.Handler);
14:
15: // Create a fake GET request for the link URI.
16: var tmpRequest = new HttpRequestMessage(HttpMethod.Get, link);
17:
18: // Send this request through the routing process.
19: var routeData = newRoute.GetRouteData(
20: Request.GetConfiguration().VirtualPathRoot, tmpRequest);
21:
22: // If the GET request matches the route, use the path segments to find the key.
23: if (routeData != null)
24: {
25: ODataPath path = tmpRequest.GetODataPath();
26: var segment = path.Segments.OfType<KeyValuePathSegment>().FirstOrDefault();
27: if (segment != null)
28: {
29: // Convert the segment into the key type.
30: key = (TKey)ODataUriUtils.ConvertFromUriLiteral(
31: segment.Value, ODataVersion.V3);
32: }
33: }
34: return key;
35: }
Deleting Links
To delete a link, add the following code to the ProductsController
class:
[!code-csharpMain]
1: public async Task<IHttpActionResult> DeleteLink([FromODataUri] int key, string navigationProperty)
2: {
3: Product product = await db.Products.FindAsync(key);
4: if (product == null)
5: {
6: return NotFound();
7: }
8:
9: switch (navigationProperty)
10: {
11: case "Supplier":
12: product.Supplier = null;
13: await db.SaveChangesAsync();
14: return StatusCode(HttpStatusCode.NoContent);
15:
16: default:
17: return NotFound();
18:
19: }
20: }
In this example, the navigation property is a single Supplier
entity. If the navigation property is a collection, the URI to delete a link must include a key for the related entity. For example:
[!code-consoleMain]
1: DELETE /odata/Customers(1)/$links/Orders(1)
This request removes order 1 from customer 1. In this case, the DeleteLink method will have the following signature:
[!code-csharpMain]
1: void DeleteLink([FromODataUri] int key, string relatedKey, string navigationProperty);
The relatedKey parameter gives the key for the related entity. So in your DeleteLink
method, look up the primary entity by the key parameter, find the related entity by the relatedKey parameter, and then remove the association. Depending on your data model, you might need to implement both versions of DeleteLink
. Web API will call the correct version based on the request URI.
|