Linq-to-SQL:忽略 WHERE 子句中的空参数
下面的查询应返回具有 ownerGroupIds 中提供的匹配 ID 或与 ownerUserId 匹配的记录。但是,如果 ownerUserId 为空,我希望忽略这部分查询。
public static int NumberUnderReview(int? ownerUserId, List<int> ownerGroupIds)
{
return ( from c in db.Contacts
where
c.Active == true
&&
c.LastReviewedOn <= DateTime.Now.AddDays(-365)
&&
( // Owned by user
!ownerUserId.HasValue ||
c.OwnerUserId.Value == ownerUserId.Value
)
&&
( // Owned by group
ownerGroupIds.Count == 0 ||
ownerGroupIds.Contains( c.OwnerGroupId.Value )
)
select c ).Count();
}
但是,当为 ownerUserId 传入 null 时,我会收到以下错误:Nullable 对象必须有一个值。
我感到一阵刺痛,我可能必须在这个例子?
The query below should return records that either have a matching Id supplied in ownerGroupIds or that match ownerUserId. However is ownerUserId is null, I want this part of the query to be ignored.
public static int NumberUnderReview(int? ownerUserId, List<int> ownerGroupIds)
{
return ( from c in db.Contacts
where
c.Active == true
&&
c.LastReviewedOn <= DateTime.Now.AddDays(-365)
&&
( // Owned by user
!ownerUserId.HasValue ||
c.OwnerUserId.Value == ownerUserId.Value
)
&&
( // Owned by group
ownerGroupIds.Count == 0 ||
ownerGroupIds.Contains( c.OwnerGroupId.Value )
)
select c ).Count();
}
However when a null is passed in for ownerUserId then I get the following error: Nullable object must have a value.
I get a tingling I may have to use a lambda expression in this instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的问题是你没有传递一个可为空的整数,你传递的是一个空值。
试试这个:
你会得到同样的错误。
如果你这样做,它应该可以工作:
your issue is that your are not passing in a nullable int, you are passing in a null.
try this:
and you get the same error.
It should work if you do this:
您是否有过 OwnerUserId null 的联系人?如果是,
c.OwnerUserId
可能为 null,并且c.OwnerUserId.Value
中没有任何值Have you some contacts with OwnerUserId null? If yes,
c.OwnerUserId
could be null and not having any value inc.OwnerUserId.Value
有条件地将 where 子句添加到表达式树怎么样?
What about conditionally adding the where clause to the expression tree?
问题:“&&”和“||”转换为类似“AndCondition(a, b)”的方法,因此“!a.HasValue || a.Value == b”变为“OrCondition(!a.HasValue, a.Value == b);”这样做的原因可能是为了获得一个适用于代码和 SQL 语句的通用解决方案。因此,请使用“?:”符号。
有关更多信息,请参阅我的博客文章:http://peetbrits .wordpress.com/2008/10/18/linq-writing-your-logic/
PROBLEM: "&&" and "||" is converted to a method like "AndCondition(a, b)", so "!a.HasValue || a.Value == b" becomes "OrCondition(!a.HasValue, a.Value == b);" The reason for this is probably to get a generic solution to work for both code and SQL statements. So instead, use the "?:" notation.
For more, see my blog post: http://peetbrits.wordpress.com/2008/10/18/linq-breaking-your-logic/