使用多个edmx(来自不同的数据库)以及工作单元和存储库模式

时间:2016-02-12 12:23:28

标签: c# entity-framework repository-pattern unit-of-work edmx

我正在开发一个包含工作单元和存储库模式的项目。现在有一个新模块,我们需要集成但具有不同的数据库和edmx。请帮助我如何扩展我的UOW和Repository以使用两个上下文。 我已经搜索了很多如何使用多个edmx。但没有得到结果(以及UOW和Repo模式)

我是UOW和Repository Pattern的新手请帮忙,下面是我的UOW和Repo:

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();
    }

下面是我的Repository实现:

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 个答案:

答案 0 :(得分:1)

组合2个(或更多)原子操作并且仍然是原子操作所需要的是事务范围。

可以找到一个非常广泛的解释here,可以找到一个非常巧妙的UOW模式实现here

基本上,您可以在TransactionScope中执行多个SaveChanges,如下所示:

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:

  

if(repositories.Keys.Contains(typeof(T))== true)

可以变成

  

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