65.9K
CodeProject is changing. Read more.
Home

Replace an Entity in Entity Framework Context

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Feb 25, 2010

CPOL
viewsIcon

17171

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:
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!