2013-06-30 63 views
0

我正在使用NHibernate,它是使用Respositories和服務抽象出來的。我們不允許使用Lazy Load屬性,因此必須在查詢中選擇它們。LINQ Lambda只選擇是否存在

我的問題是,我試圖從Answers表中獲取最新的響應編號,但在許多情況下,該對象可能不存在,所以我堅持得到空引用異常或「代碼應該無法訪問」例外。

這就是我正在做的與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次迭代,並不總是使用。首先,但有時。單

我沒有訪問存儲庫模式或任何NHibernate的查詢。有沒有辦法避免這種LINQ的空引用異常?我不能懶惰加載,所以這是一個問題。

+0

FirstOrDefault maybe? – jfin3204

+0

我試過FirstOrDefault,SingleOrDefault,Single,First,Take(1)...空引用異常或「代碼應該無法訪問」。 –

+2

這裏的縮進使得這個*真的很難閱讀...... –

回答

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 
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