When using Entity Framework, the best way to check if an object exists in the database from a performance point of view is to use
Any().
This is because
Any() will return as soon as it finds a match. Another option is Count(), but this might need to check every row before returning.
Here's an example of how to use it:
if (_context.Customer.Any(o => o.Id == _idToCheck))
{
// Match!
}
(or)
bool clientUsernameExists = _sb.Any(x => x.Username == _username);
if (clientUsernameExists)
throw Exception("The client username already exists");