我有这些模特:
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
?
答案 0 :(得分:0)
解决方法:
categoryRepository.Get(x => x.Id == categoryId,
x => x.Products.Select(p => p.Product));
这EF blog post帮了很多忙!