Search code examples
entity-frameworkodatadecoupling

Using OData with models decoupled from EF entities?


We’re considering to use OData for our next project. There are many examples out there how to use OData together with Entity Framework. These samples look pretty straightforward as long as you expose the database entities 1:1 on your REST Interface. In order to decouple our database entities from our api models, we used to map them using automapper before returning them from our repositories. This way, of course, we’re losing much of the comfort the ORM could give us. But the past teached us, using one to one representations of database entities often produced more problems than leveraging the functionalities of EF/Linq2SQL sovled, even with POCO’s.

If we want to keep the api models decoupled and think about using OData, many questions arise. OData gives much flexibility when it comes to querying resources, but all of the freedom the api client has, it has to be translated somehow down to the database. Applying the query options in-memory is obviously not an option because it requires you to load the whole table. Just supporting a few of the query options does also not seem to be the idea behind OData.

So, are we forced to expose our entities directly to our api to use OData in a meaningful way?


Solution

  • Just because you're adopting OData it doesn't necessarily follow that you have to implement the whole thing for every resource.

    I've always been a bit suspicious of the "magic box" aspects of OData. By exposing data entities as resources you are coupling a public service definition to the underlying database system. Your client integrations will be extremely vulnerable to change.

    However, this is a problem with the implementation rather than the standard itself. OData does a lot of things very well and can be a useful way of establishing syntax consistency across an API.

    You are free to implement a sub-set of query features. This is implicit in the .Net implementation as the ODataValidationSettings class allows you to specify the functions, operators and query options that you want to support. You can also take manual control over the way queries are submitted to your underlying data store by parsing the ODataQueryOptions object directly.