OData v4 API support for composite keys

I am creating an OData web service using WebAPI and OData v4.

I was able to get a service to support composite keys by overriding the SelectAction method for EntityRoutingConvention. However, this was not necessary in the previous version of OData. I personally find it pretty messy and I feel like I am reinventing the wheel.

Is there another way?

+5


source to share


2 answers


Use attribute routing.

Example:

Model:

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

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

      

Controller method for identifying an object using compound 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
}

      

Sample request:

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

      

There is no need to revoke the routing agreement.

+5


source


You can do this by prefixing "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 this from their source https://github.com/OData/WebApi/blob/master/samples/AspNetCoreODataSample.Web/Controllers/PeopleController.cs

+2


source







All Articles