Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Replace an Entity in Entity Framework Context

4.00/5 (1 vote)
24 Feb 2010CPOL 1  
I was struggling recently with a problem I KNEW had to be solvable in a much easier way than replacing ALL the fields in my managed entity by hand and then saving it. I wanted a way that I could simply replace the managed entity with a new one that had been created from an XML document.Turns...
I was struggling recently with a problem I KNEW had to be solvable in a much easier way than replacing ALL the fields in my managed entity by hand and then saving it. I wanted a way that I could simply replace the managed entity with a new one that had been created from an XML document.

Turns out it wasn't impossible and my hat goes off to the EF once again.

Basically I had to loop through the XML document creating entities from it and then compare to the DB to see if they already existed. If they did, I had to update them, else I had to add them. A simple query let me know if it existed, but the updating code is where the magic lies:

C#
var oldItem = (from c in entitiesContext.table
               where c.EntityUID == newItem.EntityUID
               select c).FirstOrDefault();

if (oldItem == null)
{
    entitiesContext.table.AddObject(newItem);
}
else
{
    entitiesContext.Detach(oldItem);
    entitiesContext.AttachTo("table", newItem);
    entitiesContext.ObjectStateManager.GetObjectStateEntry(newItem).ChangeState(System.Data.EntityState.Modified);
    entitiesContext.SaveChanges();
}



Voila! Entity replaced and saved from the generated entities.

Now I am by no means a EF guru, but this little trick let me save a TON of time on plumbing as my entities have a lot of fields that need replacing.

WARNING: Be sure the generated entities are accurate, after all, you're removing those in the data and replacing them with the generated ones!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)