Вот учебник для репозитория и UnitOfWork в EF из ASP.Net .Надеюсь, это поможет.( UnitOfWork должен гарантировать, что несколько репозиториев совместно используют один и тот же DataContext )
Общий репозиторий :
public class GenericRepository<TEntity> where TEntity : class
{
internal SchoolDBContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(SchoolDBContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
...
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
...
}
UnitOfWork : Вызов метода Save () для обновления всех ваших изменений в репозиториях.
public class UnitOfWork : IDisposable
{
private SchoolDBContext context = new SchoolDBContext();
private GenericRepository<Department> departmentRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
public void Save()
{
context.SaveChanges();
}
....
}
Контроллер :
public class CourseController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
//
// GET: /Course/
public ViewResult Index()
{
var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department");
return View(courses.ToList());
}
....
}