Return null if query is empty

S

shapper

Hello,

I am getting a record as follows:
User user = _context.Users.FirstOrDefault(u => u.Id ==
task.User.Id);

How can I make user to be null if no user is found with such an id.
At the moment I get an exception ... If I use only First I also get an
exception.

Thanks,
Miguel
 
M

Mr. Arnold

shapper said:
Hello,

I am getting a record as follows:
User user = _context.Users.FirstOrDefault(u => u.Id ==
task.User.Id);

How can I make user to be null if no user is found with such an id.
At the moment I get an exception ... If I use only First I also get an
exception.

Doesn't user come back null on the 'Default'? That's what the
FirstorDefault does is set the object to null if criteria not found.

if (user !null)
{
do something with object
}
else
{
do something if object is null
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top