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

时间:2015-04-15 10:50:50

标签: c# entity-framework ef-code-first

我有这些模特:

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还加载与Product相关的每个CategoryProduct

1 个答案:

答案 0 :(得分:0)

解决方法:

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

EF blog post帮了很多忙!