【问题标题】:EF Generic Repository Multiple IncludesEF 通用存储库多个包含
【发布时间】:2017-07-26 08:29:40
【问题描述】:

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

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    您陷入了调用返回某些内容并忽略结果的方法的典型陷阱。 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));
    

    【讨论】:

    • includes.Aggregate 很好,从没想过Aggregate 用于条件查询。
    猜你喜欢
    • 2019-05-24
    • 2020-11-10
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2015-03-21
    相关资源
    最近更新 更多