2010-09-03 104 views
1

我们有一个DateTime属性为DateDestroyed的实体。查询需要返回结果,其中此值介于可空日期时间startDateendDate之间。为什么这个LINQ Where子句不返回结果?

的WHERE子句我有【

.Where(x => startDate.HasValue ? startDate <= x.DateDestroyed : true) 
.Where(x => endDate.HasValue ? x.DateDestroyed <= endDate : true); 

查询总是返回任何结果。我很确定我没有正确编写这个查询,但不知道应该如何编写或为什么它不工作?

+0

DO您仅使用的一个得到的结果哪里? – jjnguy 2010-09-03 04:11:33

+1

您是否在查询组成后更改'startDate'或'endDate'的值? – 2010-09-03 04:16:49

+0

做任何这些答案帮助你?看起来有一个驱动器downvoter。 – 2010-09-03 22:36:34

回答

0

您可以创建/使用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>

+0

@randomDownvoter:谨慎解释你的downvote,以及这个答案如何解决问题没有帮助? – 2010-09-03 05:02:46

+0

我得到了同样的事情p.campbell,我敢肯定我的答案也会起作用。 :( – GONeale 2011-01-05 00:17:49

0

假设您有一个名为“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子句将正确地解析代码执行时。

-1

您是否总是将您的查询与应用的Where()过滤器重新分配?

这种模式应该按预期工作:

var query = getResults(); 
query = query.Where(x => startDate.HasValue ? startDate <= x.DateDestroyed : true) 
query = query.Where(x => endDate.HasValue ? x.DateDestroyed <= endDate : true); 
+0

测试过这个,但不幸的是不工作 – 2010-09-08 00:36:34

+0

我总是使用这种模式,它应该工作..?你有没有降级?我不认为我的建议值得downvote。 – GONeale 2011-01-05 00:19:00

1

我的代码需要的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; 
} 
相关问题