信息库和工作单元vs渴望加载

时间:2018-10-22 13:45:01

标签: c# entity-framework-6 eager-loading generic-repository

我知道拥有Unit Of Work是在抽象(DbContext)之上拥有抽象,并且肯定是反模式,或者至少没有必要。

我有以下问题:

我有一个通用的IRepository,如下所示:

public interface IGenericRepository<TEntity> where TEntity : class
{
    IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "");

    TEntity GetByID(object id);

    void Insert(TEntity entity);

    void Delete(object id);

    void Delete(TEntity entityToDelete);

    void Update(TEntity entityToUpdate);
}

这是此接口的实现:

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    internal GymHelperContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(GymHelperContext context)
    {
        this.context = context;
        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;
    }
}

我有一个名为Facade的实例,它实例化了Mapper和UnitOfWork,如下所示:

public class MuscleFacade
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();
        private readonly MuscleMapping _muscleMapping = new MuscleMapping();

        public MuscleFacade()
        {

        }

        public IEnumerable<MuscleViewModel> GetAllMuscles()
        {
            var source = _unitOfWork.MuscleRepository
                .Get()
                .ToList();

            var result = source.Select(x => _muscleMapping.MuscleToModel(x));

            return result;
        }

        public GymViewModel GetGymViewModel()
        {
            GymViewModel gymViewModel = new GymViewModel
            {
                ListOfMuscles = GetAllMuscles().ToList()
            };

            return gymViewModel;
        }

    }

MuscleFacade类是我使用Autofac在控制器上注入的类,我在其构造函数中注入了IMuscleFacade

现在情况是,我的MuscleTypeViewModel有一个MuscleViewModel的列表,这些模型与对应的Domain类映射,并且在这种情况下,MuscleType有很多{{1} }(例如:Arm具有二头肌,三头肌等),因此我在每个属性上都设置了导航属性,如下所示:

Muscle

现在让我们再次在Facade中查看public class MuscleType : IEntity { public int Id { get; set; } [StringLength(100)] public string MuscleTypeName { get; set; } public ICollection<Muscle> Muscles { get; set; } } public class Muscle : IEntity { public int Id { get; set; } [StringLength(100)] public string MuscleName { get; set; } public int MuscleTypeId { get; set; } public MuscleType MuscleType { get; set; } } 方法:

GetAllMuscles

如果我想快速加载MuscleType,该如何更改Get()以便接收public IEnumerable<MuscleViewModel> GetAllMuscles() { var source = _unitOfWork.MuscleRepository .Get() .ToList(); var result = source.Select(x => _muscleMapping.MuscleToModel(x)); return result; } 的{​​{1}}而不是Expression的{​​{1}}?

1 个答案:

答案 0 :(得分:4)

您可以定义一个包含您的包含定义的帮助程序类:

abstract class IncludeDefinition<TEntity>
{
    public abstract IQueryable<TEntity> Include(IQueryable<TEntity> entities);
}

class IncludeDefinition<TEntity, TProperty> : IncludeDefinition<TEntity>
{
    public IncludeDefinition(Expression<Func<TEntity, TProperty>> includeEx)
    {
        _includeEx = includeEx;
    }

    private readonly Expression<Func<TEntity, TProperty>> _includeEx;

    public override IQueryable<TEntity> Include(IQueryable<TEntity> entities)
    {
        return entities.Include(_includeEx);
    }
}

然后在您的IncludeDefinition方法中使用Get

public IEnumerable<Muscle> Get(params IncludeDefinition<Muscle>[] includes)
{
    IQueryable<Muscle> muscles = ...;
    foreach (var item in includes)
    {
        muscles = item.Include(muscles);
    }
    return muscles.ToList();
}

并调用方法

_unitOfWork.MuscleRepository
    .Get(new IncludeDefinition<Muscle, MuscleType>(m => m.MuscleType));

// Include as many as you wish
_unitOfWork.MuscleRepository
    .Get(new IncludeDefinition<Muscle, MuscleType>(m => m.MuscleType),
         new IncludeDefinition<Muscle, SomeOtherRelatedEntity>(m => m.SomeOtherProperty));

编辑此处提供了某种方式,可以“仅包含” ,而无需编写复杂的语法。

创建一个支持IQueryRepository且没有显式包含和Get的新接口Include,从此接口派生IGenericRepository

public interface IQueryRepository<TEntity>
     where TEntity : class
{
    IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null);

    IQueryRepository<TEntity> Include<TProperty>(Expression<Func<TEntity, TProperty>> referenceExpression);
}

public interface IGenericRepository<TEntity> : IQueryRepository<TEntity>
     where TEntity : class
{
    IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        params IncludeDefinition<TEntity>[] include);

    // other methods like GetByID, Add, Update...
}

更新GenericRepository定义-它使用我最初描述的方法IncludeDefinition,并在调用GenericQueryRepositoryHelper时返回Include

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


    public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
    {
        return Get(filter, orderBy, new IncludeDefinition<TEntity>[0]);
    }

    public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, params IncludeDefinition<TEntity>[] includes)
    {
        IQueryable<TEntity> query = dbSet;

        foreach (var item in includes)
        {
            query = item.Include(query);
        }

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

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

    public IQueryRepository<TEntity> Include<TProperty>(Expression<Func<TEntity, TProperty>> referenceExpression)
    {
        return new GenericQueryRepositoryHelper<TEntity>(this, new IncludeDefinition<TEntity, TProperty>(referenceExpression));
    }

    // other methods like GetByID, Add, Update...
}

在调用GenericQueryRepositoryHelper时实施Get来存储包含并应用它们

public class GenericQueryRepositoryHelper<TEntity> : IQueryRepository<TEntity>
    where TEntity : class
{
    private readonly IList<IncludeDefinition<TEntity>> _includeDefinitions;
    private readonly IGenericRepository<TEntity> _repository;

    internal GenericQueryRepositoryHelper(IGenericRepository<TEntity> repository, IncludeDefinition<TEntity> includeDefinition)
    {
        _repository = repository;
        _includeDefinitions = new List<IncludeDefinition<TEntity>> { includeDefinition };
    }

    public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
    {
        return _repository.Get(filter, orderBy, _includeDefinitions.ToArray());
    }

    public IQueryRepository<TEntity> Include<TProperty>(Expression<Func<TEntity, TProperty>> referenceExpression)
    {
        _includeDefinitions.Add(new IncludeDefinition<TEntity, TProperty>(referenceExpression));
        return this;
    }
}

高兴的查询包括:

var repo = new GenericRepository<Muscle>(...);
repo.Include(x => x.MuscleType)
    .Include(x => x.MuscleType.Muscles)
    .Get(x => x.MuscleName == "Test", x => x.OrderBy(m => m.MuscleName));