Click here to Skip to main content
11,565,623 members (39,426 online)
Click here to Skip to main content

Tagged as

Replace an Entity in Entity Framework Context

, 24 Feb 2010 CPOL 6.9K 1
Rate this:
Please Sign up or sign in to vote.
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!

License

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

Share

About the Author

RobertFall
South Africa South Africa
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionA small update Pin
Jan Kratochvíl13-Oct-13 3:28
memberJan Kratochvíl13-Oct-13 3:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 25 Feb 2010
Article Copyright 2010 by RobertFall
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid