Duplicate Key Exception from Entity Framework

Duplicate key exception from Entity Framework?

catch (UpdateException ex)
{
SqlException innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Number == ??????)
{
// handle exception here..
}
else
{
throw;
}
}

Put the correct number at ?????? that corresponds to unique constraint violation (I don't know it from the top of my head).

Duplicate Key Exception Entity Framework

When using an ORM, the SqlException is often going to be wrapped, sometimes nested quite a bit. So you need a helper function to walk the exception tree and find the SqlException (if it's there):

    static SqlException GetSqlException(Exception exception)
{
if (exception is SqlException sqlException) return sqlException;
return exception.InnerException == null ? null : GetSqlException(exception.InnerException);
}

Then, you can use whatever strategy you like for catching however fine-grained an exception, and dealing with the SqlException if it's found. e.g. based on your code:

public void AddNewStandardEngineeredModel(StandardEngineeredModel model)
{
using (context = new LabelPrintingContext())
{

try
{
context.EngineeredModels.Add(model);
context.SaveChanges();
}
catch (Exception ex)
{
var sqlException = GetSqlException(ex);

if (sqlException != null && sqlException.Errors.OfType<SqlError>()
.Any(se => se.Number == 2601))
{

// it's a dupe... do something about it
}
else
{
// it's something else...
throw;
}
}
}
}

Duplicate key value Error when updating a lot of data

  • Use FirstOrDefaultAsync
  • Where clause is redundant, you can remove it as well
    private async Task SaveFileInfos(FileInfo fileInfo)
{
//update your code to use FirstOrDefaultAsync
var foundFileInfo = await _context.FileInfos
.FirstOrDefaultAsync(f => f.FileId == fileInfo.FileId);

if (foundFileInfo == null)
{
await _context.FileInfos.AddAsync(fileInfo);
}
else
{
foundFileInfo.FileName = fileInfo.FileName;
foundFileInfo.LastModifiedDateTime = fileInfo.LastModifiedDateTime;
foundFileInfo.Path = fileInfo.Path;
}

// move this outside the for loop.
// this will round trip to Db in EVERY fileInfo, not an optimal solution.
await _context.SaveChangesAsync();
}
  • Consider calling the await _context.SaveChangesAsync(); outside the for loop
 private async Task ConvertAndSaveFiles(IDriveItemDeltaCollectionPage files)
{

foreach (var file in files)
{
await SaveFileInfos(file.Name, file.Id, file.LastModifiedDateTime,
file.ParentReference.Path);
}

// this will save everything to Db in just 1 round trip
await _context.SaveChangesAsync();
}

EF Core - error with duplicated key while adding data with unique index

There's a unique index on the dbo.Stocks table named IX_Stocks_Name. You're violating this index.

Your problem is this line:

var stock1 = new Stock("stock1");

You're creating "stock1" over and over. Instead, you should first be retrieving (or storing) the Stock entity for "stock1" and using that, if it already exists. If it doesn't exist then it's safe to create one.

In short, the code is doing an INSERT into dbo.Stocks with an existing Name.

Duplicate key error after adding data in a table with seeded entities

What I discovered is that if in the OnModelCreating method you add:

    protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<MyEntity>().Property(b => b.Id).ValueGeneratedOnAdd();
}

The database manages to understand that there is already seeded data and generates not duplicate Ids.

False Duplicate Key Error in Entity Framework Application

Your original object (the one with the "real" duplicate error) is still in the context. Doing SaveChanges after adding the "good" object later on tries to save both objects. You must remove the "bad" object you added to the context or new up a new context without the "bad" object added.

Can't insert entity Entity framework duplicate key exception

Which database do you use? If it is InMemoryDatabase from Microsoft.EntityFrameworkCore.InMemory and first animal was added with explicit id (by context.Animals.Add(new Animal { Id: 1, Name: "Cat" })) then InMemoryDatabase does not increment internal identity counter used for id setting. So when you and second animal, InMemoryDatabase try to set Id to 1 but there is already animal with this id, so exception was thrown.

You have two solution:

  • Removed explicit id from first animal (I prefer this)
  • Explicity set id in second (and all next animals)


Related Topics



Leave a reply



Submit