UnitOfWork模式的通用存储库模式

Lui*_*cia 5 c# entity-framework unit-of-work repository-pattern entity-framework-4

我正在尝试实现通用的存储库模式.我发现这个网站我觉得它很好解释. http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle

我的目的是节省开发人员一些时间和按键,我知道这将有助于我.

所以我有两个问题:
1.这是一个好方法,将来我会遇到一些问题吗?
2.如何将它与Unitofwork模式结合使用?当然,我无法创建抽象类的实例,因此以下代码无效.

public class UnitOfWork : IDisposable
    {
        #region Private fields
        private readonly MyCompanyContext _context = new MyCompanyContext();
        private GenericRepository<MyCompanyContext, Task> _taskRepository;

        public GenericRepository<MyCompanyContext, Task> TaskRepository
        {
            get
            {
                return _taskRepository ??
                         (_taskRepository = new GenericRepository<MyCompanyContext, Task>());
            }
        }




namespace MyCompany.DAL.Repository
{
    public interface IGenericRepository<T> where T : class
    {
        IQueryable<T> GetAll();
        IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
        void Add(T entity);
        void Delete(T entity);
        void Edit(T entity);
        void Save();
    }

    public abstract class GenericRepository<C, T> :
    IGenericRepository<T>
        where T : class
        where C : DbContext, new()
    {

        private C _entities = new C();
        public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }

        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }

        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = System.Data.EntityState.Modified;
        }

        public virtual void Save()
        {
            _entities.SaveChanges();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gie*_*ius 5

关于存储库有几种意见,但在我自己尝试生产各种存储库几年之后,我同意Ayende的观点,即存储库,特别是通用存储库,是冗余抽象层.

我非常喜欢这门课程:http: //www.pluralsight-training.net/microsoft/Courses/TableOfContents/linq-architecture

它走过了大多数可能的解决方案并解释了货物和坏处.

我们现在使用的是对datacontext的非常精简的抽象,只是为了克服Linq2Sql可测试性问题,这在大多数情况下使用EF时都是无关紧要的.