Search code examples
c#entity-framework-4

How to prevent Entity Framework from adding referenced objects to database on SaveChanges?


I have quite a simple situation. I've got 3 objects:

  • an object called TrainingConsultant which is not yet saved to the database
  • an object called Training which was recently saved to the database and its EntityState is Detatched.
  • an object called Consultant which was recently loaded the from database and its EntityState is Detatched.

I need to save the TrainingConsultant object with referenced Consultant and Training, so that in the database all the required fields and foreign keys are filled in properly.

The problem is that until I call context.TrainingConsultants.AddObject(trainingConsultant);, everything is in the Detached state. After that, both training and consultant have their EntityState changed to Added, so context.SaveChanges() tries to add both training and consultant to the database before adding traingingConsultant. It fails because Consultant already exists in the database, so does consultant.

How can I fix this so both Consultant and Training won't get saved but still get referenced? Keep in mind that I am assigning those 2 referenced objects somewhere else in code:

trainingConsultant.Training = training;
trainingConsultant.Consultant = consultant;

So when it comes to saving any changes would require me to save objects temporary, then set TrainingConsultant.Training and TrainingConsultant.Consultant to null?

using (var context = new Entity(Settings.sqlDataConnectionDetails))
{
    context.TrainingConsultants.AddObject(trainingConsultant);
    context.SaveChanges();
}

Solution

  • You should just specify by ID rather than attaching an entity:

    trainingConsultant.TrainingId = training.Id;
    trainingConsultant.ConsultantId = consultant.Id;
    
    context.TrainingConsultants.AddObject(trainingConsultant);
    context.SaveChanges();
    

    You can adjust as necessary to match your field/column names.