![](/img/trans.png)
[英]Entity Framework 5 - multiple DbContext and a Generic Repository class
[英]Generic Repository with different databases, entity types and dbcontext
我已按照此易於遵循的指南為asp.net Web api項目實現了一個簡單的通用存儲庫:
http://www.dataworks.ie/blog/entity_framework_5_with_automapper_and_repository_pattern
很好
但是,我在開發中的解決方案有兩個具有相同架構的簡單數據庫-用於測試/開發以及在本地(和脫機)運行時的SQL Server CE,以及在聯機時運行的SQL Azure。 兩者都有在單獨的程序集中創建的EF層。 我通過上下文類的構造函數中的web.config
連接字符串切換DbContext
。 問題出在我的控制器代碼上。
例如,如果使用Azure,我將擁有
public ActionResult Index()
{
IGenericRepository<MyProj.Data.SqlAzure.User> userRepo = new GenericRepository<MyProj.Data.SqlAzure.User>();
如果我使用的是SQL Server CE,我將擁有
public ActionResult Index()
{
IGenericRepository<MyProj.Data.SqlCe.User> userRepo = new GenericRepository<MyProj.Data.SqlCe.User>();
因此,在切換數據庫時,我必須手動更改為正確的程序集命名空間以引用我的實體。
很抱歉,如果這已經做完了,因為已經有一段時間沒有做這些了,那么這種情況下最好的/優雅的解決方案是什么? 上面的看起來很臟。 另外,我所有的通用存儲庫代碼當前都位於與Web應用程序相同名稱空間的模型文件夾中。
由於您使用的是通用存儲庫,除非您告訴它,否則它將不知道如何確定所需的用戶實體。
您可以做什么,創建一個可以為您解決問題的工廠。 GenericRepositorySqlAzure和GenericRepositorySqlCe
我想到的唯一解決方案是擁有一個工廠類,以使用配置文件中定義的開關來創建實例,例如
public DbRepositoryFactory
{
public IGenericRepository<User> GetUserRepository()
{
return ConfigurationManager.AppSettings["DbSwitch"].Equals("Azure")
? new GenericRepository<MyProj.Data.SqlAzure.User>()
: new GenericRepository<MyProj.Data.SqlCe.User>()
}
}
要么使用反射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.