I am unable to add the Deal entity because Buyer and Seller are referencing the same city "City1". I work with detached entities here because I receive the whole model through API.
// This is the result of Deal entity deserialization
var deal = new Deal
{
Id = "D1",
Buyer = new Person
{
Id = "P1",
Name = "Person1",
City = new City { Name = "City1" }
},
Seller = new Person
{
Id = "P2",
Name = "Person2",
City = new City { Name = "City1" }
}
};
_dbContext.Deals.Add(deal);
_dbContext.SaveChanges();
The error is
System.InvalidOperationException: 'The instance of entity type 'City' cannot be tracked because another instance with the same key value for {'Name'} 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.'
Here is how entities are set up:
modelBuilder.Entity<City>(x =>
{
x.HasKey(e => e.Name);
});
modelBuilder.Entity<Person>(x =>
{
x.HasKey(e => e.Id);
x.Property(e => e.Name);
x.HasOne(e => e.City).WithMany();
});
modelBuilder.Entity<Deal>(x =>
{
x.HasKey(e => e.Id);
x.HasOne(e => e.Buyer).WithMany();
x.HasOne(e => e.Seller).WithMany();
});
What is the proper way of working with such kind of entities? I use EF Core 6