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))
bool clientUsernameExists = _sb.Any(x => x.Username == _username);
throw Exception("The client username already exists");