說我有一個GenericRepository:C#MVC庫繼承和共同的DataContext
public class IGenericRepository
{
// bla bla bla
}
public class GenericRepository : IGenericRepository
{
public myDataContext dc = new myDataContext();
// bla bla bla
}
和我有類特定的資源庫:
public class CategoryRepository : GenericRepository
{
// bla bla bla
}
,並在我的控制器:
public ActionResult something()
{
CategoryRepository cr = new CategoryRepository();
GenericRepository gr = new GenericRepository();
Category cat = cr.GetMostUsedCategory();
SubCategory sub = gr.GetById(15);
// And after I make some changes on these two entities I have to:
cr.Save();
gr.Save();
}
現在,是否可以使用適用於所有存儲庫的通用數據環境?所以,當我從gr.Save()
保存它將申請cr
?我的意思是:
//Instead of
cr.Save();
gr.Save();
//I want
gr.Save(); // And my category will also be saved.
這可能嗎?
好吧,你是對的,對於這個例子我可以做到這一點,但有些情況下我必須使用不同的特定存儲庫,那麼我應該在那裏做什麼? – Shaokan
如果將相同的上下文注入到兩個存儲庫中,則調用Save將導致期望的行爲。然而,通過通過接口抽象上下文,這種模式(工作單元)變得更加明確。然後,您的控制器也將依賴此接口並決定何時調用Save。由於此接口解析爲傳遞到兩個存儲庫的上下文,因此您將獲得所需的行爲。 –