Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you abstract out your persistence code when using LINQ to SQL?

I love LINQ to SQL but it has been bugging me that in using it, my repository code becomes generated by the LINQ to SQL framework and hence tightly coupled to an SQL Server database.

Are any of you using LINQ to SQL in an abstracted, loosely coupled fashion and if so, how did you approach the problem of keeping your code database-independent?

like image 678
Nathan Ridley Avatar asked May 17 '09 18:05

Nathan Ridley


1 Answers

For myself; I'm content to re-use the object model that LINQ/dbml generates, since in reality the attributes don't hurt me, and any other implementation could provide a similar-enough model - but I don't use my data-context outside the DAL. So I have something like:

  • IFooRepository - defines the methods available using both the generated dbml objects and some POCO model classes
  • FooRepository - the implementation that knows about the data-context

My repository methods don't expose LINQ concepts like IQueryable<T> and Expression<...>, since they are leaky abstractions; other implementations will work differently (EF supports different aspects of both, for example).

Further - I've taken to marking most association properties as internal, and only using them during DAL queries (not so much during the OO work).

I could map to pure POCOs, but I don't see the benefit. I have some more thoughts on this here: Pragmatic LINQ.

like image 168
Marc Gravell Avatar answered Sep 30 '22 16:09

Marc Gravell