Error in . First(), as there is no selected result

Asked

Viewed 108 times

4

In my controller of Login I use the following code to select the user if it exists, but whenever the user type the incorrect name or password, it gives an error, because it does not find the result for the .First. I need to do a treatment, so when I find no results does not give this error.

var user = db.Usuario.First(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));

1 answer

7


There are some solutions to this, one of them is to use the FirstOrDefault().

var user = db.Usuario.FirstOrDefault(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));

Obviously you will have to treat the result later if there is no user compatible with what was informed, after all, the result will be a null if you find nothing, without a treatment, you will only be pushing the problem forward. But in doing so, you will use the normal flow. Something like:

if (user == null) return false;

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.