Gurmeet
Gurmeet

Reputation: 3314

Use multiple edmx (from different databases) along with unit of work and repository pattern

I am working on a project with unit of work and repository pattern. Now there comes a new module that we need to integrate but having different database and edmx. Please help me out how can i extend my UOW and Repository to use two contexts. I have search a lot how to use multiple edmx. but didn't get result(along with UOW and Repo Pattern)

I am new to UOW and Repository Pattern please help in this, below is my UOW and 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();
    }

below is my Repository implementation:

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

Please suggest solution how can i use two edmx with repository pattern and unit of work.

Thanks in advance.

Upvotes: 2

Views: 457

Answers (1)

Tamas Ionut
Tamas Ionut

Reputation: 4410

The thing you need to combine 2 (or more) atomic operations and still be atomic is Transaction scope.

A very broad explanation can be found here and a very neat implementation of the UOW pattern can be found here.

Basically, you can execute multiple SaveChanges within a TransactionScope like this:

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)

can be turned into

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

Upvotes: 2

Related Questions