-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
Hi,
I'm getting this error when I try to Insert domain object containing 2 level deep sub objects:
The instance of entity type 'Toy' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.
I have shared my project here: https://github.com/jarzimichal/ef7-tracking-issue/tree/master/src/EF7
Here is my code:
public abstract class Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdRow { get; set; }
}
public class Parent : Entity
{
public string Name { get; set; }
public ICollection<Child> Childs { get; set; }
}
public class Child : Entity
{
public string Name { get; set; }
public ICollection<Toy> Toys { get; set; }
}
public class Toy : Entity
{
public string Name { get; set; }
}
public static void Main(string[] args)
{
var opt = new DbContextOptionsBuilder<RootContext>();
opt.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ef7-test-db; Integrated Security=True;");
//opt.UseInMemoryDatabase();
using (IDbContext db = new RootContext(opt.Options))
{
var rep = new Repository(db);
var parent = new Parent
{
Name = "Parent",
Childs = new List<Child>
{
new Child {Name = "Child1", Toys = new List<Toy>
{
new Toy { Name = "Toy1"}, //When this line is commented, code works fine
new Toy { Name = "Toy2"},
}},
new Child {Name = "Child1"}
}
};
rep.Insert(parent);
rep.SaveChanges();
}
}
I have investigated the entity in debugger and looks like EF assigned the same '-2147482647' value to IdRow property in both Toys objects.