Reputation: 2646
I've got a query I need to perform:
return entity.Messages.Include(m => m.User)
.Include(m => m.MessageRecipients.Select(u => u.User))
.First(m => m.MessageID == messageID);
This works fine on my local machine but it breaks on the webserver, despite the same setup. The problem is that I try to include the User
Include(m => m.User)
but the user could not exist in the database anymore so it throws "Sequence contains no elements" because I use First().
Question: Is there a way to build the query in a way, so it does not brake when a user is not in DB? Something like outer join in SQL?
EDIT: If there's no User I still need the Message to be returned...
Upvotes: 0
Views: 44
Reputation: 2646
it seems that the only way was to split the query in two:
`var message = entity.Messages .Include(m => m.MessageRecipients.Select(u => u.User)) .First(m => m.MessageID == messageID);
var author = entity.Users.Where(u => u.UserID == message.AuthorUserID).FirstOrDefault();
if (author != null) message.User = author;
return message
`
Upvotes: 0
Reputation: 18181
First() will throw exception like that, if you want null or default value returned when there is no element, then try to use FirstOrDefault().
Upvotes: 1