如何急切加载 Entity Framework 中的嵌套实体?

How to eagerly load nested entities in Entity Framework?

我有这些型号:

public class Category
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<CategoryProduct> Products {get; set;}
}

public class CategoryProduct
{
    public int Id {get; set;}
    public int CategoryId {get; set;}
    public int ProductId {get; set;}
    public virtual Category Category {get; set;}
    public virtual Product Product {get; set;}
}

public class Product
{
    public int Id {get; set;}
    public string Name {get; set;}
}

我正在通过在服务层执行以下操作来加载 Category 对象和相关 Products

categoryRepository.Get(x => x.Id == categoryId, x => x.Products);

以及相应的通用存储库方法:

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

    return set.Where(predicate).FirstOrDefault();
}

在某种程度上,上述工作正常,因为我可以用一个 SQL 语句加载一个 Cateory 和相应的 Products。然而 Product 属性 每个 CategoryProduct 对象是 null.

如何让 EF 也加载与 CategoryProduct 相关的每个 Product

解决方法:

categoryRepository.Get(x => x.Id == categoryId, 
                       x => x.Products.Select(p => p.Product));

这个EF blog post帮助很大!