-1

I would like to check if the user exists with the email in the database. I want to do this in the API, it should simply return true or false. This is what i get; when the user exists it returns true if the user does not exist in DB it returns a 500 internal server error. How could I solve this? Thanks in advance

    public IHttpActionResult GetUserEmail(string Email)
    {
        var User = (db.Users
        .Where(p => p.Email == Email)
        .First());

        if (User == null)
        {
            return Ok(false);
        }
        else
        {
            return Ok(true);
        }
    }
Ewald Bos
  • 1,560
  • 1
  • 20
  • 33
  • 2
    `.First()` will throw and Exception if not existing in the `db.Users.Where()` result. You need to use `FirstOrDefault()`. https://stackoverflow.com/a/1024580/1910735 – Dawood Awan Dec 17 '21 at 10:54
  • Does this answer your question? [When to use .First and when to use .FirstOrDefault with LINQ?](https://stackoverflow.com/questions/1024559/when-to-use-first-and-when-to-use-firstordefault-with-linq) – Dawood Awan Dec 17 '21 at 10:55
  • I hope you're not developing against production, so the page showing you a 500 error should also show the actual exception and stack trace so you can debug it. Did you obtain an error, and what did it tell you? – CodeCaster Dec 17 '21 at 14:18

2 Answers2

0

The answer has been given above, I am leaving an example code block just as an example. :)

    var User = db.Users.FirstOrDefault(p => p.Email == Email);
    if (User == null)
        {
            return Ok(false);
        }
        else
        {
            return Ok(true);
        }

// or

 var User = db.Users.Any(p => p.Email == Email);
 if (!User)
 {
   return Ok(false);
 }
 else
 {
  return Ok(true);
 }
0

code block with the changes as mentioned by @Dawood Awan in the comments –

public IHttpActionResult GetUserEmail(string Email)
{
    var User = (db.Users
    .Where(p => p.Email == Email)
    .FirstOrDefault());

    if (User == null)
    {
        return Ok(false);
    }
    else
    {
        return Ok(true);
    }
}
Ewald Bos
  • 1,560
  • 1
  • 20
  • 33