我需要这样的方法,我可以在给定的实体上应用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#/ Entity Framework的这一部分的新手,我甚至不知道要搜索哪些关键字。
感谢您的帮助
答案 0 :(得分: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);
答案 1 :(得分:0)
喜欢这个吗?
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;