如何在所有Repository的泛型类上编写

时间:2016-08-22 15:45:42

标签: c# entity-framework repository repository-pattern

我想为所有Repository

编写一个通用类

我有一个实体(产品,价格,......)

和Interface IRepository

 public  interface IRepository<T> 
    {
        Dictionary<int, T> myProduct { get; set; }

        IEnumerable<T> List { get; }
        void Add(T entity);
        void Delete(T entity,int key);
        void Update(T entity,int key);
        T FindById(int Id);

    }

我可以为每个业务对象编写我的存储库,如ProudductRepository,priceReporsitory,.....

但我需要实现像这样的通用

 public class Repository<E, C> : IRepository<E>

我将这个用于我的所有业务对象而不是一个foreach实体

1 个答案:

答案 0 :(得分:0)

你可以这样做,如下所示。这只是一个例子。

创建通用存储库

namespace ContosoUniversity.DAL
{
    public class GenericRepository<TEntity> where TEntity : class
    {
        internal SchoolContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(SchoolContext 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 = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }
}

请在Implement a Generic Repository and a Unit of Work Class文章中详细了解。

更多文章:

Generic Repository and UnitofWork patterns in MVC

Generic Repository and Unit of Work Pattern