LINQ Lambda仅选择是否存在

时间:2013-06-30 20:03:37

标签: c# linq nhibernate lambda

我正在使用NHibernate,它使用Respositories和服务进行抽象。我们不允许使用延迟加载属性,因此必须在查询中选择它们。

我的问题是我正在尝试从Answers表中获取最新的响应号,但在很多情况下该对象可能不存在,所以我很难获得Null Reference异常,或者“Code应该无法访问”异常

以下是我对approprtiate部分所做的评论。

var leaders = 
    _storeService.GetAll()
                 .Where( p => p.Id.Equals(storeId) && p.Employees.Any() )
                 .SelectMany(p => p.Employees)
                 .Select(emp => new
                  {
                      LeaderId = emp.Id,
                      LeaderFirstName = emp.FirstName,
                      LeaderLastName = emp.LastName,
                      Followers = emp.Followers
                                     .Select(followers => new

{
    followers.FollowerEmployee.Id,
    followers.FollowerEmployee.FirstName,                    
    followers.FollowerEmployee.LastName,
    DepartmentName = followers.FollowerEmployee.Department.Name,

    //Problem Area
    AssessmentResponse = followers.FollowerEmployee
                                  .Answers
                                  .First( a => a.Answer.Question.IsPrimary )
                                  .Answer
                                  .Number
                                  //Null Reference Exception                                        
} )

} ).ToList();

我可能已经尝试了15次迭代,并不总是使用.First但有时候.Single

我无权访问存储库模式或任何NHibernate查询。有没有办法避免LINQ的这个空引用异常?我不能懒加载,所以这有点问题。

2 个答案:

答案 0 :(得分:2)

在EF / Linq-2-Sql中,可以通过强制转换为可空值来使其工作,因为底层SQL会进行空合并:

AssessmentResponse = (int?)followers.FollowerEmployee.Answers
    .First(a => a.Answer.Question.IsPrimary).Answer.Number

我不确定NHibernate的行为是什么,但值得一试。如果Number属性已经可以为空,您可以尝试合并它:

AssessmentResponse = (int?)followers.FollowerEmployee.Answers
    .First(a => a.Answer.Question.IsPrimary).Answer.Number ?? some default value

最后,你总是可以进行明确的检查:

AssessmentResponse = followers.FollowerEmployee.Answers.Any(a => a.Answer.Question.IsPrimary)
    ? followers.FollowerEmployee.Answers.First(a => a.Answer.Question.IsPrimary).Answer.Number ?? some default value
     : null

答案 1 :(得分:0)

而不是:

AssessmentResponse = followers.FollowerEmployee
                              .Answers
                              .First( a => a.Answer.Question.IsPrimary )
                              .Answer
                              .Number
                              //Null Reference Exception 

试试这个:

AssessmentResponse = followers.FollowerEmployee
                              .Where(a=>a.Answers != null && a.Answers
                                                              .Where(a=>a.Answer.Question.IsPrimary)
                                                              .Count > 0)
                              .Answers
                              .FirstOrDefault( a => a.Answer.Question.IsPrimary )
                              .Answer
                              .Number
                              //Null Reference Exception