I'm trying to do a deep clone of some entities. The approach mentioned in this article looks good but I run into errors. It suggests using AsNoTracking() to retrieve the entity and then to reinsert it into the context where it will cause an insert as it looks like a new object.
Here's my code:
Using ctxt As New ProductionDataEntities
Dim grade = ctxt.Grades.Include(Function(g) g.GradeWidths).AsNoTracking.First
An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.
ObjectContext you can first attach the parent object and then change object state to added. Also for each child objects, change the object state to added. You even don't need
For example for a
Category(1)↔(N)Product relation I used this code:
Using db As New SampleSystemEntities Dim c = db.Categories.Include(Function(x) x.Products).First db.Attach(c) db.ObjectStateManager.ChangeObjectState(c, EntityState.Added) For Each p As Product In c.Products db.ObjectStateManager.ChangeObjectState(p, EntityState.Added) Next db.SaveChanges() End Using
If you use
DbContext every thing will work fine using your code:
Using db As New SampleSystemEntities Dim c = db.Categories.Include(Function(x) x.Products).AsNoTracking().First db.Categories.Add(c) db.SaveChanges() End Using