Reputation: 15761
I am trying to use the Repository pattern with EF4 and I am just not sure how to make Lazy Loading work with it. If I return an object, say a Customer, and I want to be able to get at it's Orders, maybe, not for sure, how should I go about this?
How long should I let the Context live for? Should I just go back and get the collection of Orders?
Any examples would be greatly appreciated!!
Thanks!
Edit
So if I have a Repository like so (assuming I have POCO classes for Category and SubCategory):
Public Class CategoryRepository
Implements ICategoryRepository
Public Function GetCategories() As List(Of Category)
Using db As New DBContext <-- Entity Framework Context
return db.Categories.ToList()
End Using
End Function
End Class
And then consume it like this in the Controller:
Public Function Index() As ActionResult
Dim m As New CategoryViewModel
m.Categories = _Repository.GetCategories()
Return View(m)
End Function
If I try in the View to say:
Category.SubCategories.Count
It blows up saying the ObjectContext is disposed.
Upvotes: 4
Views: 2114
Reputation: 36319
If you're following the concept that Repositories exist once per aggregate, then you'll (likely) load the tree the way you'll know you will use it, in the repository. So for your example, you'd call db.Categories.Include("SubCategories") to eager-load them. You might also have different methods like "GetCategoriesDeep()" and "GetCategoriesShallow()" to differentiate if you have different scenarios.
To answer your deeper question, the context should last for a single transaction (however you define that in your app). In your case, like I say above, it seems like the correct boundary for it is the repository's method call. The controller should decide whether the user is requesting a collection w/ or w/o subcategories, and then call the right method on the repo to answer that question. T he view shouldn't have to have access to the data context (even indirectly via lazy loading).
Upvotes: 2