OData v4 WebAPI - Get entity from ODataController

802 Views Asked by At

In my OdataController I am exposing entity Customer (as an example). I have a method:

Get()

This works just fine. To return a single entity I have this method:

GetCustomer(int key)

This also works just fine.

* So here's my Question*

Is GetCustomer the only signature option to return a single entity? I'm not sure how ODataController knows how to resolve this method signature, but Im wondering if there is a generic way to define this.

1

There are 1 best solutions below

0
On

GetCustomer by default would get a Customer.Customer navigation property. Now you will save a question on stackoverflow ;) Top get a single entity you can just use Get(int/string key) as follows:

Assume db is your db context instance

[EnableQuery]
public IQueryable<Customer> Get()
{
    return db.Customers;
}

[EnableQuery]
public SingleResult<Customer> Get([FromODataUri] int key)
{
    IQueryable<Customer> result = db.Customers.Where(p => p.Id == key);
    return SingleResult.Create(result);
}

Hope it helps.