Search code examples
entity-frameworklinq-to-entitiesobjectcontextsavechanges

Insertion multiple records in the same objectContext


I'm having some trouble when I try to insert data using the same objectContext.

My problem is, the order that the Entity read my code is not the order that I "Add" it.

Example:

EntityAB has EntityA's PK as a FK. 1-N relationship.

objContext.DbSet.Add(EntityA);
objContext.DbSet.Add(EntityAB);
objContext.SaveChanges();

Error Message when the code reach SaveChanges():

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EntityAB_EntityA". The conflict occurred in database "dbTest", table "dbo.EntityA", column 'IdEntityA'.
The statement has been terminated.

So, my entity framework is reading objContext.DbSet.Add(EntityAB); before objContext.DbSet.Add(EntityA);


If I change the code to:

objContext.DbSet.Add(EntityA);
objContext.SaveChanges();
objContext.DbSet.Add(EntityAB);
objContext.SaveChanges();

It works.


But I can't. It need to be done in one SaveChanges() because of the auditing.

My question is,
CAN I OBLIGATE THE SAVECHANGES() READ THE CODE IN THE ORDER THAT I ADD IT?


Solution

  • How is your context set up?

    I think the following might work..

    in the context

    public DbSet<EntityA> EntityAs { get; set; }
    public DbSet<EntityAB EntityABs { get; set; }
    

    then in your other code

    objContext.EntityAs.Add(EntityA);
    objContext.EntityAB.Add(EntityAB);
    objContext.SaveChanges();
    

    If that doesn't work I would explore

    objContext.local