I am using Entity Framework 5 in VS.NET 2012 using a Database First approach. I’m also trying to implement a standard generic repository interface along with a Unit of Work to make sure all updates happen on a single context. Creating the repository, UoW, injecting it using DI are actually the pieces I know how to complete.
The problem I have is understanding how it correlates to the MyModel.Context.cs class below that was auto-generated from the Entity Framework 5 T4 POCO template:
public partial class AdventureWorks2008R2Entities : DbContext
{
public AdventureWorks2008R2Entities() : base("name=AdventureWorks2008R2Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Person> People { get; set; }
public DbSet<PersonPhone> PersonPhones { get; set; }
public DbSet<PhoneNumberType> PhoneNumberTypes { get; set; }
}
What I think that is to occur, is that an instance of this class is what is to be sent to the constructor of my UoW class like below:
public UnitOfWork(IContext context)
{
_context = context;
}
So my main question is, how the auto generated context class and my Repository I created (that uses UoW) are supposed to work together. I found some examples using code first in EF4, but nothing for EF5 using Database First approach with POCO generation and Repository pattern. If anyone knows of a good example on this please share.
Any help with clearing this up is appreciated, thanks!
Ok I figured one method out to solve this issue. To begin this method could actually work for Database 1st or Code 1st approaches as the Context is not modified and only an instance of it used.
Some samples have the IUnitOfWork interface being applied directly to the auto generated
AdventureWorks2008R2Entitiesclass. However you would not want to do this because modifying auto-generated code that could be overwritten is not a great idea.The idea is to have the generic repository (or if not using a generic repository each individual repository) take in an instance of the EF Context like below:
Now the IUnitOfWork Interface should declare the methods for EF and an instance of each repository type like below:
The implementation will new up an instance of the repository if it is not already instantiated like below:
public class UnitOfWork : IUnitOfWork
{
private DbContext _context;
private GenericRepository _personRepository;
private GenericRepository _personPhoneRepository;
}
Lastly, to use the Unit of Work instance for your repositories, you reach through it to the appropriate repository instance and the UoW will take care of making sure all changes saved happen on the same context: