For example, there are the following classes:
public class Detail
{
public int Id { get; set; }
public int MachineId { get;set; }
public Machine Machine { get; set; }
}
public class Machine
{
public int Id { get; set; }
public ICollection<Detail> Details { get; set; }
}
And here is a current state:
- Machine1
- Detail1
- Machine2
- Detail2
And I just want to move Detail2 from Machine2 to Machine1. Try it:
var machine1 = myDbContext.Machines
.Include(m => m.Details)
.First(m => m.Id == 1);
var machine2 = myDbContext.Machines
.Include(m => m.Details)
.First(m => m.Id == 2);
var detail2 = machine2.Details.First(d => d.Id == 2); // It still works fine
machine2.Details.Remove(detail2);
machine1.Details.Add(detail2);
myDbContext.SaveChanges(); // Exception!
System.InvalidOperationException: The instance of entity type 'MyNamespace.Detail' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.
It seems like a bug!
Or am I doing something wrong?