Entity Framework - Checking for duplicate values prior to updating the record

Could you please assist me? I am trying to update a Customer table in my database using Entity Framework (Front end calls my end point in the API to update record). Before updating the record, I need to do some validations (such as making sure that a duplicate email address is not created on the database for the customer).

Below is my current code:

if (await DuplicateEmailAddress(learnerEdit.EmailAddress)) return BadRequest("The email address is already being used for another learner.");

My method to check for duplicates:

private async Task DuplicateEmailAddress(string emailAddress) { return await _context.Learners.AnyAsync(x => x.EmailAddress == emailAddress); }

When I test my API call using Postman, I get the error message because the query is testing on the record I am updating as well. Is there a way to exclude the record that I am updating when doing the validation?

Thanks


Solution 1:

For an EF side check, you should modify your condition to exclude the entry you want to edit. Something like

_context.Learners.AnyAsync(x => x.EmailAddress == emailAddress && x.Id != learnerEdit.Id);

As commended, you should additionally add a unique constraint to the database. Otherwise your code is open to race conditions, where your DB is ok when you check but already contains a duplicate when you SaveChanges