【问题标题】:Dynamically apply filters on Entity Framework's entity using lambda expression使用 lambda 表达式在 Entity Framework 的实体上动态应用过滤器
【发布时间】:2016-07-14 19:34:06
【问题描述】:

我需要这样的方法,我可以在给定实体上应用Where(x =>x. ...)Include(x => x.RelatedEntity)OrderBy(x=>x. ...)

类似这样的:

public List<TEntity> ApplyFilter<TEntity>(TEntity entity,
                                          List<filters> filters /* List of filters: 'filters' */)
                                          where TEntity : BaseEntity
    {
        using (var db = new MyDbContext()){
        var query = db.Set<TEntity>().AsQueryable;
   //apply filters to 'query'
        query.include(/*multiple related entities*/);
        query.applyfilters(/*filters*/);

        return query.ToList();
    }
}

我需要将需要过滤/包含的内容作为 lambda 表达式传递。

注意:我搜索了很多关于如何做到这一点,但我真的找不到任何东西。我是 C#/实体框架的这一部分的新手,我什至不知道要搜索什么关键字。

感谢您的帮助

【问题讨论】:

    标签: asp.net-mvc entity-framework entity code-first


    【解决方案1】:

    您需要使用 LINQ 表达式

        public List<TEntity> ApplyFilter<TEntity>(            
            Expression<Func<TEntity, bool>> filter,
            Expression<Func<TEntity, object>> orderBy,
            params Expression<Func<TEntity, object>>[] includes) where TEntity : BaseEntity
        {
            using (var db = new MyDbContext())
            {
                var query = db.Set<TEntity>().AsQueryable();
                query = query.Where(filter);
                query = query.OrderBy(orderBy);
    
                if (includes != null)
                {
                    foreach (var include in includes)
                    {
                        query = query.Include(include);
                    }
                }
    
                return query.ToList();
            }
        }
    

    使用方法:

            ApplyFilter<TestObject>(
                x => x.Prop1 == "foo", 
                x => x.Prop2,
                x => x.Prop3, x => x.Prop4);
    

    【讨论】:

    • 其中一些是准确的,表达式,使用过滤器,例如,orderby 必须使用其他东西才能工作。类型需为Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderby,用途需为query = orderby(query)
    【解决方案2】:

    像这样?

        var result = Repository.PurchaseProposalItem.GetDbSet();
    
            if (filters.FilterByBrand) result = result.Where(p => p.GS_Product.GS_ProductBrand.PBr_Id == filters.BrandId);
            if (filters.FilterByFamily) result = result.Where(p => p.GS_Product.GS_ProductFamily.PFa_Id == filters.FamilyId);
            if (filters.FilterBySubFamily) result = result.Where(p => p.GS_Product.GS_ProductSubFamily.PSu_Id == filters.SubFamilyId);
            if (filters.FilterByProductType) result = result.Where(p => p.GS_Product.Pro_Type == filters.ProductTypeEnum);
    
        return result;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多