【发布时间】:2011-05-27 03:03:26
【问题描述】:
全部,
我需要将我的 EF 实现隐藏在存储库后面。我的简单问题:有没有办法在 DbSet 和 DbSet.Local 之间执行“查找”,而不必同时处理它们。
例如 - 我有标准的存储库实现,带有 Add/Update/Remove/FindById。我通过添加 FindByName 方法来打破通用模式(仅用于演示目的:)。这给了我以下代码:
客户端应用:
ProductCategoryRepository categoryRepository = new ProductCategoryRepository();
categoryRepository.Add(new ProductCategory { Name = "N" });
var category1 = categoryRepository.FindByName("N");
实施
public ProductCategory FindByName(string s)
{
// Assume name is unique for demo
return _legoContext.Categories.Where(c => c.Name == s).SingleOrDefault();
}
在本例中,category1 为空。
但是,如果我将 FindByName 方法实现为:
public ProductCategory FindByName(string s)
{
var t = _legoContext.Categories.Local.Where(c => c.Name == s).SingleOrDefault();
if (t == null)
{
t = _legoContext.Categories.Where(c => c.Name == s).SingleOrDefault();
}
return t;
}
在这种情况下,当查询一个新条目和一个仅在数据库中的条目时,我得到了我所期望的结果。但这提出了一些我感到困惑的问题:
1) 我会假设(作为存储库的用户)找不到下面的 cat2。但是找到了,很大一部分是cat2.Name是“Goober”。
ProductCategoryRepository categoryRepository = new ProductCategoryRepository();
var cat = categoryRepository.FindByName("Technic");
cat.Name = "Goober";
var cat2 = categoryRepository.FindByName("Technic");
2) 我想从我的存储库中返回一个通用的 IQueryable。
在存储库中包装对 DbSet 的调用似乎需要做很多工作。通常,这意味着我搞砸了。如有任何见解,我将不胜感激。
【问题讨论】:
标签: repository entity-framework-4.1 iqueryable