I am trying to get the functionality of SQL servers MERGE statement in Entity Framework.
At a WCF service, I am receiving a list of records from a client app. I want to compare a particular field in ALL the records in the list against a database table.
-Should there be a matching record in the db, I need to update the other fields in the db record.
-Should there be no match, I need to insert the whole record.
-Should there are any records in the db table that are not in the list I need to delete the records in the db.
Here is the code I am 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 elegantly achieve this?