Skip to content

InMemory - bad key management for derived entity types #19854

Closed

Description

@saliksaly

Using in-memory database, ef core 3.1. (or 3.0)
Having abstract class Animal and two derived classes: Cat and Dog.
All are registered as entities in DbContext.
Seeding 2 Cat entities in DbContext.OnModelCreating.

1st problem:
When inserting a new Cat entity to DbSet, receiving error: "ArgumentException: An item with the same key has already been added. Key: 1".
The Id for the new entity shuld be 3 because there are already two.

2nd problem:
When inserting a new Dog entity to DbSet, it behaves inappropriately: replaces Cat entity with id 1 with the new Dog entity and adds new Dog entity with id 1!

Steps to reproduce

Here is asp net core demo app to demonstarte the problem described:
https://github.com/saliksaly/aspnetcoreapp-efcore-inherited-entity-id-problem

Further technical details

EF Core version: 3.1.0
Database provider: Microsoft.EntityFrameworkCore.InMemory
Target framework: .NET Core 3.1
Operating system: Win10 v. 1809
IDE: Visual Studio Community 2019 16.4.4

Activity

  1. ajcvickers commented on Feb 12, 2020

    @ajcvickers
    Contributor

    @saliksaly I was able to reproduce this and it does look like a bug.

    Note for team: it looks like the code that peeks into the in-memory database to decide what key value to use is not working correctly when there is inheritance mapping.

  2. self-assigned this
    on Feb 14, 2020
  3. added this to the 5.0.0 milestone on Feb 14, 2020
  4. saliksaly commented on Feb 17, 2020

    @saliksaly
    Author

    Hi, would not be there any workaround until 5.0.0 version?
    Maybe something similar to DbContextExtensions.ResetValueGenerators in #6872?

  5. ajcvickers commented on Feb 25, 2020

    @ajcvickers
    Contributor

    @saliksaly Just wanted to let you know that I have started investigating a workaround, but it may take me a while.

  6. added a commit that references this issue on Mar 6, 2020
    449e056
  7. ajcvickers commented on Mar 6, 2020

    @ajcvickers
    Contributor

    @saliksaly I have a PR out to fix this for EF Core 5.0. Here's a workaround for 3.1:

    private static void BumpGenerator(
        DbContext context, Type entityClrType, string propertyName, int newLowBound)
    {
        var entityType = context.Model.FindEntityType(entityClrType);
        var property = entityType.FindProperty(propertyName);
        var options = context.GetService<IDbContextOptions>().FindExtension<InMemoryOptionsExtension>();
        var inMemoryStore = context.GetService<IInMemoryStoreCache>().GetStore(options.StoreName);
        var generator = inMemoryStore.GetIntegerValueGenerator<int>(property);
        
        var values = new object[entityType.GetDeclaredProperties().Count()];
        values[property.GetIndex()] = newLowBound;
        generator.Bump(values);
    }

    Use it like this:

    BumpGenerator(context, typeof(AnimalBase), nameof(AnimalBase.Id), 2);
    
    context.Add(
        new Cat
        {
            Name = "Tom",
        });

    Passing 2 here means that the next value generated will be 3.

    Note: this workaround uses EF internal code. This code will change in new releases of EF Core and the workaround will likely break. Use only with EF Core 3.1.

  8. added 2 commits that reference this issue on Mar 16, 2020
    0a50002
    e0b950a
  9. added a commit that references this issue on Mar 19, 2020
    2972c62
  10. modified the milestones: 5.0.0, on Mar 31, 2020
  11. ShoSashko commented on May 8, 2020

    @ShoSashko

    @ajcvickers
    I just wanted to clarify. I have the same issue but with string as a key.
    EF Core version: 3.1.0
    Database provider: Microsoft.EntityFrameworkCore.InMemory
    Target framework: .NET Core 3.1

    {"An item with the same key has already been added. Key: [email protected]"}

    Please let me know if there is any workaround?

  12. ajcvickers commented on May 9, 2020

    @ajcvickers
    Contributor

    @ShoSashko There is a workaround posted above.

  13. ShoSashko commented on May 11, 2020

    @ShoSashko

    @ajcvickers Thanks for the quick response.

    Not sure how I can apply this workaround for my specific case, having a string as a PK.
    I've tried to change the workaround posted above from int to string

    private static void BumpGenerator(
        DbContext context, Type entityClrType, string propertyName, string newLowBound)
            {
                var entityType = context.Model.FindEntityType(entityClrType);
                var property = entityType.FindProperty(propertyName);
                var options = context.GetService<IDbContextOptions>().FindExtension<InMemoryOptionsExtension>();
                var inMemoryStore = context.GetService<IInMemoryStoreCache>().GetStore(options.StoreName);
                var generator = inMemoryStore.GetIntegerValueGenerator<string>(property);
    
                var values = new object[entityType.GetDeclaredProperties().Count()];
                values[property.GetIndex()] = newLowBound;
                generator.Bump(values);
            }
    

    But it throwing exception of the generator.Bump.

    I have doubts that it will work anyway, there is no equal method for GetIntegerValueGenerator for the string.

    Please let me know if I am even on the right track.

  14. ajcvickers commented on May 11, 2020

    @ajcvickers
    Contributor

    @ShoSashko No, this code doesn't make sense for strings, but then usually automatically generating string key values also doesn't make sense. You may be running into this breaking change.

  15. saliksaly commented on Jun 11, 2020

    @saliksaly
    Author
  16. modified the milestones: , 5.0.0 on Nov 7, 2020
  17. removed their assignment
    on Sep 1, 2024
  18. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions