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

4

In my controller login I use the following code to make the user selection if it exists, however whenever the user types the incorrect name or password, an error because it does not find the result for .First . I need to make a treatment, so when you do not find any results do not give this error.

var user = db.Usuario.First(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));
    
asked by anonymous 04.12.2015 / 20:25

2 answers

6

There are some workarounds for this, one of them is to use 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 you were informed, after all, the result will be null if you do not find anything, without a treatment, you will only be pushing the problem forward. But doing so, will use the normal flow. Something like:

if (user == null) {
    return false;
}
    
04.12.2015 / 20:32
-1

That way it worked.

 int countUser = db.Usuario.Where(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha)).Count();

        if (countUser != 0)
        {
            var user = db.Usuario.First(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));
        }

Is it a good practice?

    
04.12.2015 / 20:34