Entity Framework - include in subquery? - Part 2

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)
{
    // Retrieve member path:  
    List<PropertyInfo> members = new List<PropertyInfo>();
    EntityFrameworkHelper.CollectRelationalMembers(path, members);

    // Build string path:  
    StringBuilder sb = new StringBuilder();
    string separator = "";
    foreach (MemberInfo member in members)
    {
        sb.Append(separator);
        sb.Append(member.Name);
        separator = ".";
    }

    // Apply Include:  
    return query.Include(sb.ToString());
}

How can this be adapted to provide a strongly typed form:

context.Restaurant.Include("MenuCategory.MenuItems");
+2
source share
2 answers

I have a hint that allows you to do just that: Tip 28 - How to implement a loading strategy with impatience

Uses a great trick that I think.

Alex

+4
source

, :

var list = dataContext.CartLists.Include(typeof(CartListItem).Name).Where(l => l.CustNum == customerNumber && l.ListTypeID == (int)ShoppingCartType.WebShoppingCart).Single();

., , EF, . , , EF, - , , , , .

+1

Source: https://habr.com/ru/post/1721721/


All Articles