我正在尝试开发用于查询ef核心的扩展方法。我有这个扩展程序:
public static class FiltrExtension
{
public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter)
{
if (!string.IsNullOrWhiteSpace(filter.OrderType))
query.Where(x => x.OrderType == filter.OrderType);
return query;
}
}
然后我尝试过滤数据,但是扩展方法什么也不做:
var data = await _uow.DatabaseContext.Contract.Filtr(filter).ToListAsync();
有人可以帮忙吗?
答案 0 :(得分:3)
您应像这样将query.Where(x => x.OrderType == filter.OrderType);
的结果放入query
public static class FiltrExtension
{
public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter)
{
if (!string.IsNullOrWhiteSpace(filter.OrderType))
query = query.Where(x => x.OrderType == filter.OrderType);
return query;
}
}
答案 1 :(得分:0)
您必须返回结果:
public static class FiltrExtension
{
public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter)
{
if (!string.IsNullOrWhiteSpace(filter.OrderType))
var result = query.Where(x => x.OrderType == filter.OrderType);
return result;
}
}
您可以使用正则表达式:
public static IQueryable<Contract> And<Contract>(this IQueryable<Contract> source, Expression<Func<Contract, bool>> predicate)
{
return source.Where(predicate);
}