通用存储库包含和过滤

时间:2018-02-07 18:53:21

标签: c# asp.net-mvc entity-framework generics

我创建了一个通用的存储库。目前我有一个继承自我的通用(Repository)的StaffRepository。 这很有效,因为我的通用存储库具有我的CRUD操作,并允许我在我的服务中使用这些,以及我的StaffRepository中的方法,该方法对上下文执行额外的过滤并添加包含。 但是,我需要为每个实体创建一个Repository(大多数按ClientId过滤和主键)。 有没有办法可以使用通用方法进行过滤和应用包含? 我也在这里采用正确的方法吗?谢谢你的帮助。

StaffRepository示例:

 public class StaffRepository : Repository<Staff>
{
    public StaffRepository(ApplicationDbContext _context) : base(_context)
    {
    }

    public async Task<List<Staff>> GetAsync(int clientId)
    {
        return await _context.Staff
            .Include(s => s.Person)
            .Include(u => u.Person.User)
            .Include(p => p.Photograph)
            .Where(x => x.ClientId == clientId)
            .ToListAsync();
    }

    public async Task<Staff> GetByIdAsync(int clientId, int staffId)
    {
        return await _context.Staff
            .Include(s => s.Person)
            .Include(u => u.Person.User)
            .FirstOrDefaultAsync(x => x.ClientId == clientId && x.StaffId == staffId);
    }
}

我的通用存储库:

public class Repository<T> : IRepository<T> where T : class, new()
{
    internal readonly ApplicationDbContext _context;

    public Repository(ApplicationDbContext context)
    {
        this._context = context;
    }

    public async Task<T> FindAsync(int id)
    {
        return await _context.Set<T>().FindAsync(id);
    }

    public async Task InsertAsync(T entity)
    {
        await _context.Set<T>().AddAsync(entity);
        await SaveAsync();
    }

    public async Task AddRangeAsync(IEnumerable<T> entities)
    {
        await _context.Set<T>().AddRangeAsync(entities);
        await SaveAsync();
    }

    public async Task UpdateAsync(T entity)
    {
        _context.Set<T>().Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
        await SaveAsync();
    }

    public async Task DeleteAsync(T entity)
    {
        if (_context.Entry(entity).State == EntityState.Detached)
            _context.Set<T>().Attach(entity);
        _context.Set<T>().Remove(entity);
        await SaveAsync();
    }

    public async Task SaveAsync()
    {
        await _context.SaveChangesAsync();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要做的就是使用表达式,就像您在下面的GetAsync方法中看到的那样:

public class GenericRepository<TEntity> where TEntity : class
    {
        internal DbContext dbContext;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(DbContext context)
        {
            this.dbContext = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual async Task<IEnumerable<TEntity>> GetAsync(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "",
            int first = 0, int offset = 0)
        {
            IQueryable<TEntity> query = dbSet;

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

            if (offset > 0)
            {
                query = query.Skip(offset);
            }
            if (first > 0)
            {
                query = query.Take(first);
            }

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

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

我刚刚将存储库包含在GetAsync方法中,我建议您使用UnityOfWork模式,这样您就可以将该存储库的实例(针对每个实体)放在集中的位置,例如:

public class UnitOfWork : IDisposable
    {
        private GenericRepository<YourEntity> yourRepository;

        private DbContext context;

        public UnitOfWork(DbContext context)
        {
            this.context = context;
        }

        public GenericRepository<YourEntity> YourRepository
        {
            get
            {
                if (this.yourRepository== null)
                {
                    this.yourRepository= new GenericRepository<YourEntity>(context);
                }
                return yourRepository;
            }
        }
}

然后这只是一个实例化它的示例:

await unitOfWork.YourRepository.GetAsync(filter: w => w.OtherKeyNavigation.Id == 123456, includeProperties: "OtherKeyNavigation", first: 20, offset: 0);

注意:我不包括存储库和UnityOfWork中的所有代码,因为这不是此问题的一部分。 谢谢