2010-01-05 86 views
0

我正在使用以下代碼從我的數據庫中使用實體提取數據。如果沒有找到記錄,它會拋出下面的異常「對象引用未設置爲對象的實例」。我可以捕捉到這一點,以阻止它導致問題,但寧願修改代碼以避免出現問題。我可以更改Linq查詢以便更寬容嗎?當沒有東西要返回時,Linq會拋出異常

  using (var ctx = new MyEntities()) 
      { 
       var users = ctx.NotificationMessages.Include("NotificationUsers") 
           .Where(x => x.Priority == priority) 
           .FirstOrDefault().NotificationUsers 
           .ToList(); 
      } 

回答

6

的問題是,FirstOrDefault可以返回null,你需要檢查的是:

var notificationMessage = ctx.NotificationMessages.Include("NotificationUsers") 
          .Where(x => x.Priority == priority) 
          .FirstOrDefault(); 

if (notificationMessage != null) { 
    var users = notificationMessage.NotificationUsers.ToList(); 
    // ... 
} 
0
.FirstOrDefault().NotificationUsers 

那麼這是可以預料的。你沒有空檢查!

0

FirstOrDefault返回nul lif沒有結果。你可以寫

var message = ctx.NotificationMessages.Include("NotificationUsers") 
          .Where(x => x.Priority == priority) 
          .FirstOrDefault(); 
var users = message == null ? new List<User>() : message.NotificationUsers.ToList(); 

,或者你可以寫

var users = (ctx.NotificationMessages.Include("NotificationUsers") 
          .Where(x => x.Priority == priority) 
          .FirstOrDefault() ?? new NotificationMessage()).NotificationUsers.ToList(); 
0

你可以打破你的查詢,並檢查空。此外,Where是不必要在這裏:

 using (var ctx = new MyEntities()) 
     { 
      var nm = ctx.NotificationMessages.Include("NotificationUsers") 
          .FirstOrDefault(x => x.Priority == priority); 
      IList<NotificationUser> users = null; 
      if (nm != default(NotificationMessages)) 
       users = nm.NotificationUsers.ToList(); 
      else 
       users = new List<NotificationUser>(); 
      // ... 
     } 
0

你可以寫:

 using (var ctx = new MyEntities()) 
     { 
      var users = (ctx.NotificationMessages.Include("NotificationUsers") 
          .Where(x => x.Priority == priority) 
          .Select(x => x.NotificationUsers) 
          .FirstOrDefault() ?? Enumerable.Empty<NotificationUsersType>()) 
          .ToList(); 
     } 
相關問題