I am testing bulk import using EF Core and trying to save asynchronously.
I am trying to add 100 objects at a time and then asynchronously save and repeat until they are saved. Sometimes I get a PK error because it is trying to add two objects with the same identifier to the database. None of the added objects has an identifier; identifiers are sequences that are automatically generated.
The code:
public async Task<bool> BulkAddAsync(IEnumerable<VehicleCatalogModel> models)
{
_dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
try
{
var entities = models.Select(ToEntity);
_dbContext.Set<VehicleCatalog>().AddRange(entities);
await _dbContext.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError(0, ex, "An Error occurred during the import");
return false;
}
return true;
}
I call the method in the xunit test, which generates a list of test data and calls the import
var result = manager.BulkAddAsync(modelsToAdd.AsEnumerable());
var counter = 0;
while (!result.IsCompleted && counter < 10)
{
Thread.Sleep(6000);
counter++;
}
Assert.True(result.IsCompleted && result.Result);
100 , , , . - , , ? ?