我有以下
Linq lambda表达式:
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() }); }
当用户未登录时,此函数中的用户变量为null.这不应该是一个问题,因为短路布尔评估应该处理这个问题.问题是,它没有!而是抛出System.NullReferenceException.
当用户为null时,HttpContext.Current.Request.IsAuthenticated返回false.我通过注释引用用户变量的括号部分来检查这一点,然后表达式正确评估.