EF通用存储库多个包含

时间:2017-07-26 08:29:41

标签: c# entity-framework-core

想法是拥有一个适用于所有实体的通用存储库。 我设法做到了,但如果我需要有一个应该包含一个或多个其他实体的方法,那么我就有问题。 我在代码中提出了一些想法,但这对我不起作用。 另外我一直在考虑在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();
        }
    }

1 个答案:

答案 0 :(得分:8)

你已经陷入了调用返回某些东西并忽略结果的方法的典型陷阱。行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));
相关问题