简体   繁体   中英

How to load nested entities without lazy loading in Entity Framework?

I have the following model:

public class Order 
{
    public int Id {get; set;}
    public int Number {get; set;}
    public virtual ICollection<OrderDetail> Details {get; set;}
}

public class OrderDetail
{
    public int Id {get; set;}
    public int OrderId {get; set;}
    public virtual Product Product {get; set;}
}

public class Product
{
    public int Id {get; set;}
    public int Number {get; set;}
    public string Description {get; set;}
}

In my OrderRepository, I load a complete order like this:

public override Order Get(int id)
{
    return base.Get(id, x => x.Details);
}

And the base method is:

public virtual T Get(int id, params Expression<Func<T, object>>[] include)
{
    if (include.Any())
    {
        var set = include.Aggregate<Expression<Func<T, object>>, IQueryable<T>>
                  (dbSet, (current, expression) => current.Include(expression));

        return set.SingleOrDefault<T>(x => x.Id == id);
    }

    return dbSet.Find(id);
}

The above works partially fine because it loads the Order and the OrderDetails. However, I also want to load the related Product for every Detail so that I can display the product description in the list too.

How can I improve on the above method to allow me to do so?

Just add another argument with nested Select :

public override Order Get(int id)
{
    return base.Get(id, x => x.Details, x => x.Details.Select(z => z.Product));
}

See MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM