efcore icon indicating copy to clipboard operation
efcore copied to clipboard

id/primary key mapping is not working in version 3.0.1

Open aspirinv opened this issue 7 years ago • 3 comments

Adding of the related record into the context causes exception if there is already an entity with the same Id

Steps to reproduce

  1. Retrieve record (start tracking)
  2. Create entity linked to the record with the same Id
  3. Add created entity into DbSet

Result: System.InvalidOperationException: 'The instance of entity type 'Client' 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.'

        static void Main(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<Context>()
                .UseInMemoryDatabase(databaseName: "InMemory_db")
                .UseLoggerFactory(LoggerFactory.Create(l => l.AddConsole()));

            AddFakeParentIssue(optionsBuilder.Options);
        }

        private static void AddFakeParentIssue(DbContextOptions<Context> options)
        { 
            var client = new Client { Name = "John" };
            using (var context = new Context(options))
            {
                context.Clients.Add(client);
                context.SaveChanges();
            }

            using (var context = new Context(options))
            {
                var john = context.Clients.FirstOrDefault();
                var post = new Post { Client =  new Client { Id = john.Id }, Text = "Hello" };

                context.Posts.Add(post);
                context.SaveChanges();
            }        
        }

The same code works well in EF Core 2.2.6. The issue is only reproduced on the 3.0.1

Further technical details

EF Core version: 3.0.1 Database provider: Microsoft.EntityFrameworkCore.InMemory Target framework: .NET Core 3.0 Operating system: Windows 10 IDE: Visual Studio 2019 16.3

aspirinv avatar Dec 03 '19 10:12 aspirinv

The behavior in 2.2 is actually a bug. The new Client instance set on Post is being discarded and instead the currently tracked instance is being used. This can be seen by setting some other property of the new instance. For example:

var john = context.Clients.FirstOrDefault();
var newJohn = new Client { Id = john.Id, Name = "Ted" };
var post = new Post { Client =  newJohn, Text = "Hello" };

context.Posts.Add(post);
context.SaveChanges();

Since the new Client instance is discarded it means the change of the name to "Ted" will never be saved. A query on a new context instance after making this change:

var post = context.Posts.Include(e => e.Client).ToList();

shows that Client.Name is still set to "John".

ajcvickers avatar Dec 03 '19 23:12 ajcvickers

Thanks for clarification. The bug in the 2.2 is understandable, but what would be the actions to make functionality work? Is there a setting that should be set to move the entity entry to the Modified state, instead of throwing an exception?

aspirinv avatar Dec 04 '19 08:12 aspirinv

@aspirinv Typically by not creating a new instance:

var john = context.Clients.FirstOrDefault();
var post = new Post { Client =  john, Text = "Hello" };

context.Posts.Add(post);
context.SaveChanges();

ajcvickers avatar Dec 04 '19 19:12 ajcvickers