Greg Bacchus
Greg Bacchus

Reputation: 2466

EF4.1 override SaveChanges for only certain entity types

I am wanting to override ObjectContext.SaveChanges for only certain entity types, and leave the default behavior for everything else. I can find the entities that need to be saved,

I tried this,

   public override int SaveChanges()  
    {  
        ChangeTracker.DetectChanges();  
        ChangeTracker.Entries<JobField>().ToList().ForEach( c => { /* write data here */ c.State = EntityState.Unchanged; } );  
        return base.SaveChanges();  
    }

But I get the following error

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.

  1. How do I convince it that everything is OK.
  2. If there are things that dependencies that need to be saved by the default SaveChanges, how do I execute them first?

Thanks

Upvotes: 2

Views: 1072

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

You will not execute anything first. EF has very strict state machine for changing state of entities and relations. Once any entity is in unexpected state (state not allowed by state machine logic) the exception will be thrown before any changes are persisted.

You probably did some complex changes and modified states in inconsistent way. It is hard to say where is the problem because your code snippet shows nothing about changes you did but this exception most commonly happens if state of your entities is not consistent with state of relations among them. Relations can have also state and change tracker is not able to manipulate it.

Upvotes: 2

Related Questions