因此,在解决这个问题几个小时后(以及我们朋友 Google 的一些帮助),我找到了一个可行的解决方案来解决我的问题。我创建了以下 Linq 表达式扩展:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace MyCompany.MyApplication
{
public static class LinqExtensions
{
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
}
}
此扩展允许像这样创建 Linq 查询:
var products = context.Products.WhereIf(!String.IsNullOrEmpty(name), p => p.Name == name)
.WhereIf(startDate != null, p => p.CreatedDate >= startDate)
.WhereIf(endDate != null, p => p.CreatedDate <= endDate);
这允许每个 WhereIf 语句仅在满足提供的条件时才影响结果。该解决方案似乎有效,但我总是对新想法和/或建设性批评持开放态度。