我们有一个具有DateTime属性DateDestroyed
的实体。查询需要返回该值介于可为空的DateTimes、startDate
和endDate
之间的结果。
我拥有的where子句是:
.Where(x => startDate.HasValue ? startDate <= x.DateDestroyed : true)
.Where(x => endDate.HasValue ? x.DateDestroyed <= endDate : true);
查询始终不返回任何结果。我很确定我没有正确地编写这个查询,但是不知道它应该如何编写,或者为什么它不能工作?
发布于 2010-09-03 12:24:02
您可以为WhereIf
创建/使用扩展方法
给定一个布尔条件,追加一个Where
子句。
var foo = db.Customers.WhereIf(startDate.HasValue,
x => startDate <= x.DateDestroyed)
.WhereIf(endDate.HasValue,
x => x.DateDestroyed <= endDate );
更多细节请访问WhereIf at ExtensionMethod.net。你可以在那里找到IEnumerable<T>
和IQueryable<T>
的代码。
发布于 2010-09-08 08:41:09
我的代码需要IQueryable,所以我在ExtensionMethod.net对@p.campbell的工作进行了如下修改:
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
return condition ? source.Where(predicate).AsQueryable() : source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
return condition ? source.Where(predicate).AsQueryable() : source;
}
发布于 2010-09-03 12:14:55
假设您有一个名为"query“的变量,它存储了linq语句的开头部分。尝试这样动态构造where子句:
if (startDate.HasValue) {
query = query.Where(x => x.DateDestroyed >= startDate);
}
if (endDate.HasValue) {
query = query.Where(x => x.DateDestroyed <= endDate);
}
LINQ在延迟执行时工作,因此WHERE子句将在代码执行时正确解析。
https://stackoverflow.com/questions/3632971
复制相似问题