繁体   English   中英

EF通用存储库多个包含

[英]EF Generic Repository Multiple Includes

想法是拥有一个适用于所有实体的通用存储库。 我设法做到了,但如果我需要有一个应该包含一个或多个其他实体的方法,那么我就有问题。 我在代码中提出了一些想法,但这对我不起作用。 另外我一直在考虑在EF中使用聚合函数,但我从未使用过。 有人可以指导我如何管理这个吗?

  public interface IRepository<T> where T : BaseEntity
    {
        IEnumerable<T> GetAll();
        T Get(Int64 id);
        void Insert(T entity);
        void Delete(T entity);
        Task<bool> SaveChangesAsync();
        T SearchByName(Expression<Func<T, bool>> predicate);
        IEnumerable<T> GetAll(string[] includes);

    }



public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private Entities.AppContext _context;
        private DbSet<T> entities;

        public Repository(Entities.AppContext context)
        {
            _context = context;
            entities = _context.Set<T>();
        }

        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            entities.Remove(entity);
        }

        public T Get(long id)
        {
            return entities.SingleOrDefault(s => s.Id == id);
        }

        public IEnumerable<T> GetAll()
        {
            return entities.ToList();
        }

        public IEnumerable<T> GetAll(string[] includes)
        {
            foreach (string include in includes)
            {
                entities.Include(include);
            }
            return entities;
        }

        public void Insert(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            entities.Add(entity);
        }

        public async Task<bool> SaveChangesAsync()
        {
            try
            {
                return (await _context.SaveChangesAsync()) > 0;
            }
            catch (Exception ex)
            {

                return false;
            }

        }

        public T SearchByName(Expression<Func<T, bool>> predicate)
        {
            return entities.Where(predicate).SingleOrDefault();
        }
    }

你已经陷入了调用返回某些东西并忽略结果的方法的典型陷阱。 entities.Include(include); 什么都不做 - 类似于entities.Where(...); entities.Select(...); 等等

正确的代码是这样的:

var query = entities.AsQueryable();
foreach (var include in includes)
    query = query.Include(include);
return query;

或者使用单行Aggregate

return includes.Aggregate(entities.AsQueryable(), (query, path) => query.Include(path));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM