Entity Framework 如何在不延迟加载的情况下加载嵌套实体?

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

我有以下型号:

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;}
}

在我的 OrderRepository 中,我加载了一个完整的订单,如下所示:

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

基本方法是:

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);
}

上面的部分工作正常,因为它加载了 Order 和 OrderDetails。但是,我也想为每个细节加载相关的产品,以便我也可以在列表中显示产品描述。

我如何改进上述方法以允许我这样做?

只需添加另一个嵌套参数 Select:

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

MSDN