views:

124

answers:

5

I am using the following code to extract data from my database using entities. If a record isn’t found it throws the following exception “Object reference not set to an instance of an object.” I can catch this to stop it causing problems but would rather modify the code to not have the problem. Can I change the Linq query so that it is more tolerant ?

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

The problem is that FirstOrDefault can return null, and you need to check for that:

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

if (notificationMessage != null) {
    var users = notificationMessage.NotificationUsers.ToList();
    // ...
}
Mark Byers
A: 
.FirstOrDefault().NotificationUsers

Well that is to be expected. You have no null check!

leppie
A: 

FirstOrDefault returns nul lif there are no results. You can write

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

or you could write

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

You could break your query and check for null. Also, Where is unnecessary here:

       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>();
           // ...
       }
bruno conde
A: 

You could write:

       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();
       }
nikie