Search code examples
c#restodataodatalibodata-connected-service

How can I build a OData client based on a shared model (POCO classes)?


In my project I am using OData v3 and v4 (ASP.NET Web API with Entity Framework in the back). Currently I built a client using the Visual Studio tools.

But is there another way? Do I really have to build a client based on the $metadata and the toolset?

Is it possible to share my model (contract) by a shared library and build a client like this:

var client = new ODataClient<MySharedModel>(uri);
MySharedModel.Product product = 
  client.Products.Where(p => p.Category.Name == "Vegetables").FirstOrDefault();

The model can be a set of my own DTO objects which I can map to the equivalent entity framework objects.

My goal is, to share a well-documented model (source code XML documentation) with additional logic such as a ToString implementation and additional properties. Further more I save a additional step: generating a client (this sucks when you build and publish all your packages automatically on TFS Build server).

Is this possible for OData v3 or OData v4?


Solution

  • OData has recently started reviving and the team is regularly releasing new updates of the OData Connected Service entity generator, so you might want to consider giving it another shot.
    You can definitely reuse the same model, but then you'd lose client-specific features that are generated for you, for example a dedicated container with all entity-sets as properties, collection properties exposed as ObservableCollection<T>, as well as self-tracking entities, as well as others.

    All classes are generated as partial classes, so you can always extend them by adding methods into your own parts, which can, for this matter, also be shared classes.

    Regarding the documentation, it's not supported at the moment, but this has been suggested and seems to be considered for future development.

    Anyway, it's definitely possible, and shouldn't be to hard using your own entities.
    To learn how to facilitate OData client access using your client POCOs, I'd recommend generating the model once and keep the code off your project or as excluded files, just for the reference, so you can mimic a similar functionality that works for you. That was the most helpful way to me.

    Additionally, you will benefit from having a look at the documentation and the API reference docs, which has been a bit refreshed lately.