通用存储库筛选器子属性

时间:2016-12-16 06:38:38

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

我正在使用通用存储库来查询我的数据库here。我的所有实体都继承了一个具有属性Active的基类,当用户删除它时,我将Active设置为false。我现在面临的问题是,虽然下面的代码适用于主要实体,但我无法弄清楚如何仅返回Active子活动。

我尝试过使用动态linq但没有成功。有没有办法做到这一点,除了最明显的使用linq对子实体?

 public virtual TEntity GetById(object id,
        Expression<Func<TEntity, bool>> filter = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = DbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }
        if (includeProperties.Length > 0)
        {
            query = includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
        }
        else
        {
            return DbSet.Find(id);
        }

        if (query.Any())
        {
            return query.First();
        }
        return query.First();
    }

2 个答案:

答案 0 :(得分:1)

您应该为其创建过滤器(EntityFramework.Filters):

public interface IActive
{
    public bool Active {get;set;}
}

public class MyClass : IActive
{
    public int Id {get;set;}
    public bool Active {get;set;}
}

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{   
    modelBuilder.Conventions
       .Add(FilterConvention.Create<IActive, bool>("MyFilter", (entity, Active) => entity.Active);
}

<强>用法:

var filter = context.EnableFilter("MyFilter");
filter.SetParameter("Active", true);

var item = GetById(1);
//now inside GetById method 'item' and all it's children will be filtered with "Active == true" condition

context.DisableFilter("MyFilter");

答案 1 :(得分:0)

其中一个选择:

public virtual TEntity GetById(object id,
        Expression<Func<TEntity, bool>> filter = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = GetActive();

        if (filter != null)
        {
            query = query.Where(filter);
        }
        if (includeProperties.Length > 0)
        {
            query = includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
        }
        else
        {
            return DbSet.Find(id);
        }

        if (query.Any())
        {
            return query.First();
        }
        return query.First();
    }

public virtual IQueryable<TEntity> GetActive()
{
    return 
        DbSet.Where(a => a.Active);
}