在LINQ的lambda表达式布尔短路评价 [英] Boolean shortcircuit evaluation in Linq lambda expression
问题描述
我有以下的Linq lambda表达式:
I have the following Linq lambda expression:
private IEnumerable<SubjectSelectorSubjectGroup> GetSubjectList()
{
User user = db.Users.Find(WebSecurity.CurrentUserId);
return db.RequiredSubjects.Where(r => !r.Subject.Name.Contains("Home"))
.GroupBy(r => r.Subject)
.OrderByDescending(r => r.Count())
.Select(r => new SubjectSelectorSubjectGroup()
{
SubjectId = r.Key.SubjectId,
SubjectName = r.Key.Name,
IsInFavourites = HttpContext.Current.Request.IsAuthenticated &&
(user.Elective1 != null && user.Elective1.SubjectId == r.Key.SubjectId ||
user.Elective2 != null && user.Elective2.SubjectId == r.Key.SubjectId ||
user.Elective3 != null && user.Elective3.SubjectId == r.Key.SubjectId),
Occurrences = r.Count()
});
}
当用户没有在那么用户登录在这个函数
变量为空。这不应该是监守短路布尔评估的应的问题处理这个。现在的问题是,它不!相反, System.NullReferenceException
被抛出。
When the user is not logged in then the user
variable in this function is null. This should not be a problem becuase short-circuit boolean evaluation should deal with this. The problem is, it doesn't! Instead, a System.NullReferenceException
is thrown.
当用户为空的HttpContext。 Current.Request.IsAuthenticated
返回false。我已经被注释掉括号部分引用用户
变量,然后表达正确评估检查这一点。
When the user is null HttpContext.Current.Request.IsAuthenticated
returns false. I have checked this by commenting out the bracketed section that references the user
variable, and then expression evaluates correctly.
有谁知道为什么 Sql的Linq
试图取消引用用户
变量在这种情况下,当它不应该实际上是必要的?有没有人有一个工作围绕这个问题?
Does anyone know why Linq to Sql
tries to dereference the user
variable in this situation when it shouldn't actually be necessary? Does anyone have a work around for this issue?
推荐答案
整个表达式转换为和评估的SQL,这意味着&放大器;&安培;
运营商不淡预期短路
The entire expression is translated to and evaluated as SQL, which means that the &&
operator is not short circuited as expected.
您可以建立一个列表解决问题,或在 ElectiveX.SubjectId
,你要搜索,然后使用 tmpList.Contains(r.Key.SubjectId)
在查询中。这将被翻译成凡(...)
SQL表达式。
You can solve the problem by building a list or array of the ElectiveX.SubjectId
that you want to search for and then use tmpList.Contains(r.Key.SubjectId)
in the query. That will be translated into a WHERE IN (...)
SQL expression.
这篇关于在LINQ的lambda表达式布尔短路评价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!