In Entity Framework (specifically EF 3.5, but if it exists in EF 4 it gives me a reason to upgrade) is it possible to lazy load only part of a collection? I may be approaching this wrong too, so I'm open to suggestions. My tables/entities look similar to this:
Person PersonMeal Meal
------ 1---* ---------- *---1 -----
ID ID ID
... PersonID ...
MealID
Value
...
I have a list of Person objects that have been retrieved through Entity Framework via a stored procedure. I have a view that only shows one Meal at a time, so I only want the information related to that meal. Currently I have code that looks like this:
Function GetPersons() As List(Of Person)
Dim personList = context.StoredProcedureCall(param1, param2, param3).ToList()
personList.ForEach(Function(x) LazyLoadProperties(x))
Return personList
End Function
' Work around function because VB lambdas don't take Sub's
Function LazyLoadProperties(ByVal person As Person) As Object
If (Not person.PersonMeal.IsLoaded) Then
person.PersonMeal.Load()
End If
Return Nothing
End Function
The issue is this is loading up the entire collection. Granted it's a small collection so worst case scenario I can load it all up and then remove all but the one I need, but that is far from ideal. Plus I'm not sure if it would be possible without triggering any of the events of modifying the collection since they shouldn't have been in there in the first place.
Personhave a many-to-many relationship withPersonMealandPersonMealhave a many-to-many relationship withMealas shown in your question? Or doesPersonrather have a many-to-many relationship withMeal, while thePersonMealis the connecting table? If so, there shouldn't be an entity generated forPersonMeal. I've also noticed aValuefield, however. Could you clarify your data structure a bit? A screenshot of your EDM could be helpful, as well as your database structure.PersonEntitytable, but no entity generated. ThePersonentity should have a collection ofMealsand theMealentity should have a collection ofPeople. Did you generate your model from the database or create it yourself in the designer? And what is theValueproperty for (that might be the reason EF is generating thePersonMealentity)?PersonMealsrather thanPersonMealsince it is a collection. Regarding your question: 'I have a view that only shows one Meal at a time, so I only want the information related to that meal'. How do you determine which meal exactly to load and show?