Code Silverback
Code Silverback

Reputation: 3214

LINQtoSQL , repository pattern and lazy load

How do you use LINQtoSQL with the repository pattern?

I’m new to L2S and find its lazy loading to be a real impediment to using the repo pattern.

Usually, I think of the repository pattern like this:

var myCustomer = null;

using (var myRepo = new Repo()){
    myCustomer = myRepo.GetCustomerForCustomerId(123);
}

if(myCustomer.Orders.Any()){
 //do something
}

Trouble is, won’t L2S attempt to make a data connection when myCustomer.Orders is interrogated? Doesn’t this lead to unpredicatable database access issues?

I mean, yes, I could tell my repo to verify orders inside of the repo confident that our complete test coverage verifies that developers never call an entity we didn't explicitly load, but I would rather just get rid of the lazy loading/object-datacontext persistence.

So I have 4 options

  1. Create domain objects that get created from the L2S objects – lots of work and maintainance
  2. Create derived verisons of my L2S object that break he linkage (http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx)
  3. Use LLBLGenPro instead.
  4. Appeal to the wisdom of stack overflow readers

I’m going with 4 for now.

How do I ensure that my objects wont call the db after my repo is closed?

And yes, I did read every stack question that talks about L2S and Repos and none of them answer this question.

Upvotes: 2

Views: 378

Answers (1)

shaunmartin
shaunmartin

Reputation: 3919

Sometimes it is useful to eager-load an entity's children. You can do so with DataLoadOptions.LoadWith which tells your DataContext to automatically load an entity's children when the parent entity is loaded.

Snippet from the MSDN link above:

Northwnd db = new Northwnd(@"c:\northwnd.mdf");
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Customer>(c => c.Orders);
db.LoadOptions = dlo

You can also use DataLoadOptions.AssociateWith to further customize the behavior of the automatic loading.

Upvotes: 1

Related Questions