全部,如何將EF 4.1 DbContext包裝到存儲庫中?
我有一個要求隱藏我的EF實現後面的存儲庫。我的簡單問題:是否有辦法在DbSet和DbSet.Local之間執行「查找」,而不必同時處理它們。
例如 - 我有添加/更新/刪除/ 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();
}
在這個例子中,組別爲空。
但是,如果我實現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。通常,這意味着我搞砸了。我會很感激任何見解。
謝謝您的回答。我非常同意你所有的點,但有一件事我一直運行到什麼要告訴我的版本庫的消費者。在我工作的地方在這裏,一個非常非正式調查證實,用戶會希望能夠獲得新的對象返回查詢後。有人告訴我「NHibernate的工作原理」就是這樣。我懶得證實我自己。如果是這樣的話,那麼ORM的選擇將是語義泄漏到倉庫的使用。哦,這就是生活。再次感謝您的幫助。 – basilard99 2011-05-31 14:32:19
@basilard99查詢後?如果您保存上下文狀態,你可以有EF從數據庫讀取的ID和產生的數據和對象返回給調用方法。 – 2011-05-31 23:13:59