实体框架的最佳实践包括"包括"在存储库中

时间:2014-04-07 18:12:48

标签: entity-framework repository-pattern

我有产品实体的存储库模式,我有一个按ID检索产品的方法。每种产品都有一个类别,以及其他复杂的属性。在某些情况下,我想要检索没有类别(延迟加载)的产品,但在某些情况下我想要返回两个实体(产品和类别)。有两种方法有更好的选择吗?这就是我编码的内容:

Product GetById(int id) 
{ 
     // without includes
     ... 
}

Product GetByIdFull(int id) 
{ 
     // with includes
     ...
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

public Product Get(int id, params Expression<Func<TEntity, object>>[] propertiesToInclude)
{
    var query = context.Products;
    foreach (var expression in propertiesToInclude)
    {
        query = query.Include(expression);
    }
    return query.SingleOrDefault(p => p.id == id);
}

调用代码可以选择使用lambda来指定要包含的属性,如下所示:

var justProduct = repo.Get(productId);
var productAndCategory = repo.Get(productId, p => p.Category);
相关问题