2016-02-12 53 views
1

我正在使用工作單元和存儲庫模式的項目。現在出現了一個我們需要集成但具有不同數據庫和edmx的新模塊。請幫助我如何擴展我的UOW和Repository以使用兩個上下文。 我已經搜索了很多如何使用多個edmx。但沒有得到結果使用多個edmx(來自不同數據庫)以及工作單元和存儲庫模式

我是新來UOW和存儲庫模式,請在這方面的幫助,下面是我的UOW和回購(UOW爲和回購模式一起):

private DBEntities entities = null; 

    public Dictionary<Type, object> repositories = new Dictionary<Type, object>(); 

    public UnitOfWork() 
    { 
     entities = new DBEntities(); 
    }   

    public IRepository<T> Repository<T>() where T : class 
    { 
     if (repositories.Keys.Contains(typeof(T)) == true) 
     { 
      return repositories[typeof(T)] as IRepository<T>; 
     } 
     IRepository<T> repo = new Repository<T>(entities); 
     repositories.Add(typeof(T), repo); 
     return repo; 
    } 

    public void SaveChanges() 
    { 
     entities.SaveChanges(); 
    } 

下面是我的倉庫執行:

public DbContext context; 
     public DbSet<T> dbset; 

     public Repository(DbContext context) 
     { 
      this.context = context; 
      dbset = context.Set<T>(); 
      } 
     public T GetById(int id) 
     { 
      return dbset.Find(id); 
     } 

請提出解決辦法,我怎麼可以用兩個EDMX與工作的倉庫模式和單位。

在此先感謝。

回答

1

你需要結合2個(或更多)原子操作並仍然是原子的東西是事務範圍。

一個非常廣泛的解釋可以找到here和UOW模式的一個非常整潔的實現可以找到here

using (var scope = new TransactionScope()) 
{ 
    repo1.SaveChanges(); 
    repo2.SaveChanges(); 
    scope.Complete(); 
} 


public class AggregateRepository 
{ 
    private readonly Dictionary<Type, IRepository> repositories; 

    public AggregateRepository() 
    { 
     //... initialize repositories here ... 
    } 

    public void Add<T>(T entity) 
    { 
     repositories[typeof(T)].Add(entity); 
     // mark repositories[typeof(T)] somehow 
    } 

    public void SaveChanges() 
    { 
     using (var scope = new TransactionScope()) 
     { 
      foreach(markedRepository) 
      { 
       markedRepository.SaveChanges(); 
      } 
      scope.Complete(); 
     } 
    } 

PS:

如果(repositories.Keys.Contains(typeof運算(T))== TRUE)

基本上,可以像這樣一個TransactionScope內執行多個的SaveChanges

可以變成

if(repositories.ContainsKey(typeof(T)))

+0

但我不確定如何將它適用於我當前的UOW和Repository模式。 – Gerry

+0

鑑於您需要兩個存儲庫,您可以創建一個包含「簡單」存儲庫列表的AggregateRepository。基本上你需要一個[Type-> SimpleRepo]的字典。無論何時您想通過兩個(或更多)簡單存儲庫更新兩個(或更多)實體,AggregateRepository中的SaveChanges將SaveChanges()調用包裝在TransactionScope中的簡單倉庫。 –

相關問題