I am not sure if this is correct, I am sure that someone will tell me if this is not so.
Yesterday I asked a question ( Entity Framework - Include in sub query? ), Which was answered very well and it solved my problem. But I think there might be a better way, so I'm going to ask a question, but a little differently.
Let's say I have 3 tables:
Restaurant 1 ..... M MenuCategory 1 ..... M MenuItem I have a L2E request that looks something like this:
Restaurant = context. Restaurant. Include (r => r.MenuCategory) .FirstOrDefault (r => r.RestaurantId == resaurantId); This works to some extent, but only preloads menu categories.
What I really want to do is something like:
Restaurant = context.Restaurant
.Include(r => r.MenuCategory)
.Include(r => r.MenuCategory.MenuItems)
.FirstOrDefault(r => r.RestaurantId == resaurantId);
But it is clear that this is not available as r.MenuCategory is enumerated
... the work around is to use standard notation:
context.Restaurant.Include("MenuCategory.MenuItems");
... but it's not very typed. This question is finding a strongly typed answer
This is the current extension method:
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> query, Expression<Func<T, object>> path)
{
List<PropertyInfo> members = new List<PropertyInfo>();
EntityFrameworkHelper.CollectRelationalMembers(path, members);
StringBuilder sb = new StringBuilder();
string separator = "";
foreach (MemberInfo member in members)
{
sb.Append(separator);
sb.Append(member.Name);
separator = ".";
}
return query.Include(sb.ToString());
}
How can this be adapted to provide a strongly typed form:
context.Restaurant.Include("MenuCategory.MenuItems");