当没有任何回报时,Linq抛出异常

时间:2010-01-05 12:27:40

标签: linq-to-entities

我使用以下代码使用实体从我的数据库中提取数据。如果未找到记录,则会抛出以下异常“对象引用未设置为对象的实例。”我可以捕获此信息以阻止它导致问题,但宁愿修改代码以避免出现问题。我可以更改Linq查询以使其更宽容吗?

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

5 个答案:

答案 0 :(得分:6)

问题是FirstOrDefault可以返回null,您需要检查:

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

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

答案 1 :(得分:0)

.FirstOrDefault().NotificationUsers

那是可以预料的。你没有空检查!

答案 2 :(得分: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();

答案 3 :(得分:0)

您可以中断查询并检查null。此外,此处不需要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>();
           // ...
       }

答案 4 :(得分: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();
       }