Search code examples
c#asp.net-web-apilinq-to-sqlodata

using LinqToSql with OData WebApi?


We have a project that uses LinqToSql as its ORM and We'd like to expose our entities using OData version 4 (thus as far as I have learned we can't use WCF Data Services and we should use Web Api instead).

So far I couldn't find any example or documentation on the Net that shows how to use LinqToSql along with OData WebApi.

The problem is ODataConventionModelBuilder works with EntityFramework ( Actually it default set of conventions works with DataComponentModel annotations which are not used in our LinqToSql entities)

I am looking for a ODataModelBuilder that works with System.Data.Linq.Mapping to make the model.

The other solution is to find the correct set of conventions for ODataConventionModelBuilder that works with LinqToSql mapping annotatoins.

I don't know if this model builder exists or should we implement it ourselves ?


Solution

  • There is no off-the-shelf model builder for Linq to SQL. There are several different ways you can solve your problem.

    • Derive from ODataModelBuilder a custom builder class that recognizes the annotations defined in System.Data.Linq.Mapping.

    • Build the model manually using the methods of the stock ODataModelBuilder.

    • Build a set of data transfer classes that represent the exact types and properties you want to expose through your service, and then write a utility for transforming data transfer objects to data storage objects, and vice versa. In the data transfer layer, the classes can adhere to the conventions recognized by ODataConventionModelBuilder (e.g., key properties are named Id or FooId for a class named Foo). The transformation utility can be written easily with the help of a library like AutoMapper. See ASP.NET WebApi OData support for DTOs, DTO and Projections in WebAPI, and Web API Deep Dive - DTO Transformations and Automapper.