Home > Back-end >  ASP.NET Core Web API and Entity Framework simultaneously check if entity exists in database
ASP.NET Core Web API and Entity Framework simultaneously check if entity exists in database

Time:05-26

I'm developing an ASP.NET Core Web API project using Entity Framework. API requests are constantly coming from a source and I receive them, I check with linq whether the account number field has been added to the database before, if not, I add it, but sometimes 20 requests can come from the API source at the same time and duplicate records may occur.

How can I prevent this situation?

var account = dbContext.Accounts
                       .FirstOrDefault(x => x.AccountNumber == apiMessage.AccountNumber);

if (account is null)
{
    account = new Account();
    account.AccountNumber = apiMessage.AccountNumber;
}

CodePudding user response:

Just handle it in database side to make it easy. Add Unique constraint in the AccountNumber column.

You can handle the migration in your EF configuration

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Account>()
        .HasIndex(u => u.AccountNumber)
        .IsUnique();
}

CodePudding user response:

You can wait for the controller to finish before starting a new one (No concurrent calls), but that will not be a good solution.

If you do that, the requests will either wait for their turn, which decreases performance.

Or they will not run at all if the controller is already working, which will result in a controller not answering all the requests.

  • Related