Search code examples
asp.net-web-apiodataasp.net-web-api-odata

Newbie on webapi odata


Vendor asks to expose a rest api as odata, trying to understand how it works in odata world, my assumption is the data model present themselves as entities, which then enables filter by query string, but how would a odata query work on a relational data model, e.g. on customer orders, I cannot simply join the entire customer and order table then return the entire dataset! (or maybe I could just return them as paged data?) could someone point out some best practice for designing odata webapis? much appreciated!! thanks!!!


Solution

  • I guess, you are using Entity Framework as a Model for OData. so

    return Ok(myDb.Customers)
    

    would do the trick for a multiple row fetch.

    Basically, $expand (JOIN on other tables) and $filter and $select are automagically applied using your whole EF model.

    But if you fear that private data or secure data would be exposed, you have to apply prefiltering. return Ok(myDb.Customers.Where(w => w.CustomerId == myCustomerId))

    Odata has built in settings to avoid it to return say, 10.000 rows. You are quite free configuring that all. But expect some learning curve because after all, you might need extra modelling and navigation property optimization.

    In addition, you have by default on an OData controller, GET/POST/PUT/PATCH/DELETE methods, but you also might want custom functions/actions that you have to define.

    On Github, Microsoft has quite some samples.

    https://github.com/OData/ODataSamples/tree/master/WebApi/v4