使用 lambda 表达式对 Entity Framework 的实体动态应用过滤器

Dynamically apply filters on Entity Framework's entity using lambda expression

我需要这样的方法,我可以在给定实体上应用 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();
    }
}

我需要将我需要的 filtered/included 作为 lambda 表达式传递。

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

感谢您的帮助

像这样?

    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;

您需要使用 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);