I am trying to get the functionality of MERGE SQL servers in the Entity Framework.
In the WCF service, I get a list of entries from the client application. I want to compare a specific field in ALL records in a list with a database table.
-If there is a corresponding entry in db, I need to update the other fields in the db entry.
-If there is no match, I need to insert the whole record.
-If there are entries in the db table that are not in the list, I need to delete the entries in db.
Here is the code I'm struggling with so far.
//List of people from whatever source List peopleList = GetListOfPeopleFromClient(); using (var ctx = new PeopleEntities()) { foreach (var person in peopleList) { var dbPerson = ctx.People.FirstOrDefault(p => p.FirstName == person.FirstName); if (dbPerson == null) { dbPerson = new Person { FirstName = person.FirstName, LastName = person.LastName }; ctx.People.AddObject(dbPerson); } else { dbPerson.LastName = person.LastName; } } //============ //Yet to figure out how to do: //delete from People where person.FirstName NOT in peopleList.FirstNames //=========== ctx.SaveChanges(); }
My question is: how do you gracefully achieve this?
anon
source share