Entity Framework 6 Data Graphs Re-Inserting Records

While working with EF for loading data using transactions, I came across a unique scenario. Records were being inserted into tables, which was not the intended result I was looking to accomplish. Luckily, I ran into one of  Julie Lerman's posts from 2013, which helped explain the issue and confirm that my logic for fixing the issue in the past was somewhat correct, but more importantly showed me the right way for handling the issue. Usually when this happens, the unwanted entity that is being inserted can either be removed or set to null within the graph (Parent entity) or simply setting the foreign key for the parent entity of the child entity that is unfortunately being inserted. Today this did not work. I tried nulling out the child entity and for some reason EF did not add a foreign key during generation, rather just the object itself to the parent entity.

Luckily Julie mentions the correct way of handing the issue which is to Attach the object to the EF context first, and then add it to the parent entity object that really needs to be inserted. Below shows how I fixed it. Not the most obvious as Julie hints as well

//The "If" condition prevents the same object being "Attach" more than once
if (!projectId.Equals(clientProject.ProjectId))
{//EF wants to know when ClientProject records already exist so EF does not insert them.
	//new clientProject object that has not been attached
	clientProject = new ClientProject { ProjectId = e.ClientProject.ProjectId }; 
	//Attache the object to the DbContext
//Set the object to the parent entity. 
//But dont worry because it is now attached and flagged as 'unchanged'. 
//If we did not attach it above, ClientProjects would be inserted 
e.ClientProject = clientProject; 
//now insert the parent object...no ClientProjects should be inserted now
_repository.Insert<TimeEntry>(e);    //Helper method for attaching the entity, which is called above public void Attach<T>(T entity) where T : class { DbContext.Set<T>().Attach(entity); }  //Helper method for inserting the entity into the database public void Insert<T>(T entity,bool saveChanges= true) where T : class { DbContext.Set<T>().Add(entity);         if (saveChanges)         DbContext.SaveChanges(); } 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: BayerWhite
Posted on: 12/2/2015 at 4:31 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed


Comments are closed