yardpenalty yardpenalty - 20 days ago 5
C# Question

How to design multiple repositories that access the same real-time data using EF?

I am actually looking for some help on learning the ropes on designing multiple Repositories that will access the same database using EF. I have seen sample code where each repository has it's own private DBContext, but am having difficulty with this concept. I am not interested in a Generic Interface in this project.

I want multiple interfaces where one is

Identity
based (on authorization) and other job specific repositories such as Categories, Items, etc in a single application where the inherited interfaces are reusable, hence the multiple
DbContext
instances.

In SQL you have transactions where you may commit or rollback the transaction, so in EF would multiple repos access the same (real-time) data? Maybe a better question would be how should I design my DAL when I want a single application to inherit many job specific repositories.

What did jgauffin mean by,
" make sure that your repository is 100% complete abstraction"

What is meant by this? Also here is an example of what I am trying to figure out. Is this practice reasonable?

public class OneRepo: IRepository, IDisposable
{

private DbContext context = new DbContext();

// Methods and whatnot...

}


And then a second repository also requires the same db connection by OneRepo but has separate in-memory Unit of Work I think?

public class AnotherRepo: IRepository, IDisposable
{

private DbContext context = new DbContext();

// Methods and whatnot...
}


I apologize if my question is not well-written. I am relatively new to actually posting and I am not sure if I am making myself clear. I have already decided that I am not fond of generic repos in general and would like to create repos based on authorization and/or user tasks using Role Interface pattern. Any help explaining would be greatly appreciated!

Answer

You inject the data context into your repositories

public class FirstRepo
{ 
   DbContext _ctx;

   public FirstRepo( DbContext ctx )
   { 
       this._ctx = ctx;
   }
}

public class AnotherRepo
{ 
   DbContext _ctx;

   public AnotherRepo( DbContext ctx )
   { 
       this._ctx = ctx;
   }
}

This way you can pass the same context to all repositories under the same unit of work.

Comments