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.

5
  • 1
    you might want to change the order in which you are saving so no key konstrains are created
    – COLD TOLD
    Mar 31, 2014 at 15:39
  • Well, i also tried to insert the data manually in the table(same as i was doing in the code) and everything got inserted with any error. Something is wrong with linq. Apr 1, 2014 at 8:55
  • 1
    You don't need to Add the items, they are already in the context. You just need to change their state. Apr 2, 2014 at 15:00
  • ok guys, i managed to fix the issue. @COLDTOLD you are right i changed the order and things worked. Apr 3, 2014 at 12:08
  • @HonorableChow thanks. I was doing the mistake that you mentioned. I just changed the state to Added and then no need to do AddObject. Apr 3, 2014 at 12:08

1 Answer 1

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.