0

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...

2 Answers 2

1

First() will throw exception like that, if you want null or default value returned when there is no element, then try to use FirstOrDefault().

Sign up to request clarification or add additional context in comments.

3 Comments

will FirstOrDefault() still return the Message with the User property null? Or will the query return null?
The query will return null.
any idea on how to write this query to still return the instance of the Message?
0

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

`

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.