id/primary key mapping is not working in version 3.0.1
Adding of the related record into the context causes exception if there is already an entity with the same Id
Steps to reproduce
- Retrieve record (start tracking)
- Create entity linked to the record with the same Id
- 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
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".
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 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();