This project implements the Repository pattern for Entity Framework.
Nuget package: https://www.nuget.org/packages/EntityFramework.Repository
Please have a look at the test project for an actual working implementation on how to use the library.
Below is a brief quick start guide.
Follow the steps below to use the repository in a database first scenario:
- Create the EDMX model as you normally would using Visual Studio
- Create a partial class of the DB context in the step above and implements
IDbContext. For example:
publicpartialclassTestDbEntities:IDbContext{}- The repository is now ready to use.
Here is a very basic way to use it without dependency injection:
using(varcontext=newTestDbEntities())using(varcontextAdapter=newContextAdaptor<IDbContext>(context))using(varunitOfWork=newUnitOfWork<IDbContext>(contextAdapter)){varaccountRepository=newRepository<IDbContext,Account>(contextAdapter);accountRepository.Insert(account);unitOfWork.SaveChanges();}In case of code first, here are the steps:
- Create your context, make it inherits
DbContextand implementsIDbContext - Create your domain classes as you normally would with EntityFramework.
- The repository is now ready to use. Use it the same way as with the database first scenario above.
Normally, every UnitOfWork.SaveChanges() would be executed in a transaction. If you would like to manage the transaction manually, use IUnitOfWorkSession.
using(varsession=unitOfWork.StartSession()){transactionRepository.Insert(transaction);unitOfWork.SaveChanges();accountRepository.Insert(account);unitOfWork.SaveChanges();session.Commit();}Below is an example on how to register and use with Autofac as the IoC container.
- Registration
varbuilder=newContainerBuilder();builder.RegisterAssemblyTypes(typeof(IDbContext).Assembly).AsImplementedInterfaces().InstancePerLifetimeScope();builder.RegisterGeneric(typeof(ContextAdaptor<>)).AsImplementedInterfaces().InstancePerLifetimeScope();builder.RegisterGeneric(typeof(UnitOfWork<>)).AsImplementedInterfaces().InstancePerLifetimeScope();builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)).InstancePerLifetimeScope();varcontainer=builder.Build();- How to use
varaccountRepository=container.Resolve<IRepository<IDbContext,Account>>();varunitOfWork=container.Resolve<IUnitOfWork<IDbContext>>();