question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

EF Core AddRange and entities with duplicate keys

See original GitHub issue

I have a use case where a third party provides an enumeration of items that I wish to merge into a database using EF Core. There are use cases where the third party provides an item with the same key more than once in the enumeration.

Id Account LastPayment
12345 ABC123 1/1/2021
23456 BCD234 2/1/2021
12345 ABC123 2/1/2021

Ideally, I would like BOTH updates to 12345 to take place (we audit history in the data tier).

I get an error when attempting to add 12345 twice to the same context. Code POC is:

[Fact]
public async Task HandlesDuplicateKeys()
{
    var services = new ServiceCollection()
        .AddDbContext<ItemContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString()))
        .BuildServiceProvider();

    var items = new List<ItemA>()
    {
        new ItemA() { Id = 1, A = "Foo" },
        new ItemA() { Id = 1, A = "Bar" }
    };

    using (var context = services.GetRequiredService<ItemContext>())
    {
        context.AList.AddRange(items);
        await context.SaveChangesAsync();
    }
}

public class ItemA
{
    public int Id { get; set; }
    public string? A { get; set; }
}

public class ItemContext : DbContext
{
    public RepositoryContext(DbContextOptions<RepositoryContext> options) : base(options)
    { }

    public DbSet<ItemA> AList { get; set; }
}

yields:

Message: System.InvalidOperationException : The instance of entity type ‘ItemA’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.

What’s the appropriate way to manage this use case?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:10 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
stevendarbycommented, Apr 27, 2021

I think SetValues sets all matching properties and may not meet your “non-null properties” requirement, so some reflection might be required (assuming you’re aiming to code once for multiple types and not just ItemA)

1reaction
rojicommented, Apr 27, 2021

@epatrick you don’t need to call SaveChanges on a per-item basis - note that it’s outside of the loop in the above samples. You’re indeed correct that batching multiple updates in a single SaveChanges can be important for performance.

Read more comments on GitHub >

github_iconTop Results From Across the Web

EF Core AddRange and entities with duplicate keys
I have a use case where a third party provides an enumeration of items that I wish to merge into a database using...
Read more >
EF Core AddRange and entities with duplicate keys ...
Coding example for the question EF Core AddRange and entities with duplicate keys-entityframework core.
Read more >
Why is EF core 5.0 inserting duplicate records
Why is Entity Framework 5.0 inserting duplicate records in the Database in uncertain behavior when using AddAsync() method for adding data.
Read more >
Ef Core - weird behavior of AddRange
When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using > ' ...
Read more >
Entity Framework Extensions AllowDuplicateKeys
The BulkOperation.AuditEntries property gets or sets if a duplicate key is possible in the source. The following example chooses a Name ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found