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

Ret*_*der 0 linq-to-entities

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

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

Mar*_*ers 6

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

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

if (notificationMessage != null) {
    var users = notificationMessage.NotificationUsers.ToList();
    // ...
}
Run Code Online (Sandbox Code Playgroud)