3

I am using Linq to entities for general CRUD operations. Recently, i had a scenerio where i have to duplicate the whole record in the database (with different primary keys in all the related tables). My DB structure is pretty simple. I have a main table (lets say A) and other tables (lets say B, C, D). The main table holds the primary keys of table B,C,D as foreign keys.

I fetch a record from the database that i have to duplicate. Then i

1) change its object state to "Added" using context.objectStateManager.ChangeObjectState(AObj,EntityState.Added)

2) add the object in context using context.AddToA(AObj)

3) then i do saveChanges()

everything works fine on table A and properly new object is inserted.

If i do the same steps on Tables B,C,D i get an exception

1) change its object state to "Added" using context.objectStateManager.ChangeObjectState(AObj.B,EntityState.Added) //Here i access the child table B

2) add the object in context using context.AddToA(AObj)

3) then i do saveChanges()

The objectContext might be in an inconsistent state. A referential integrity constraint voilation occured. The property values that defines the refrential constraint are not consistent between principal and dependent objects in a relationship.

Behroz Sikander
  • 3,885
  • 3
  • 22
  • 36

1 Answers1

0

Read the object graph using AsNoTracking(), then it is just a matter of adding it and saving, no worries about order or state, I used this to implement a SaveAs feature in a recent project:

        var myGraph = tableA.Where(c => c.Id == id)
            .Include(c => c.childA)
            .Include(c => c.childB)
            .Include(c => c.childC)
            .AsNoTracking()
            .FirstOrDefault();

        if (myGraph != null)
        {
            myGraph.CopiedFromId = id;

            myGraph = Context.Set<TableA>().Add(myGraph);

            Context.SaveChanges();
        }

Here is a discussion on AsNoTracking()

Community
  • 1
  • 1
Tommy Grovnes
  • 4,126
  • 2
  • 25
  • 40