5
votes

I am building an OData Web Service using WebAPI and OData v4.

I was able to get the service to support composite keys through overriding the SelectAction method of the EntityRoutingConvention. However, in previous version of OData this was not needed. I personally believe it’s pretty messy and I feel like I am reinventing the wheel.

Is there any other way?

2

2 Answers

5
votes

Use attribute routing.

An example:

Model:

public class Product
{
    [Key]
    public int ID { get; set; }

    [Key]
    public string Name { get; set; }
}

Controller method for identifying the entity using composite keys:

[EnableQuery]
[ODataRoute("Products(ID={key1},Name={key2})")]
public IHttpActionResult Get([FromODataUri] int key1, [FromODataUri] string key2)
{
    // You business logic for retrieving the entity from your storage using the two keys and return
}

Request sample:

GET http://host/service/Products(ID=1,Name='Car')

No need to override routing convention.

3
votes

You can do this with the prefix "key" out of the box:

[EnableQuery]
public IHttpActionResult Get([FromODataUri] int keyID, [FromODataUri] string keyName)
{
    // You business logic for retrieving the entity from your storage using the two keys and return
}

I just checked with Microsoft.AspNet.OData v7.0.1

You can find it their source https://github.com/OData/WebApi/blob/master/samples/AspNetCoreODataSample.Web/Controllers/PeopleController.cs