title: Synchronize Records using Entity Framework
body: <p>I am trying to get the functionality of SQL servers <a href="http://technet.microsoft.com/en-us/library/bb510625.aspx" rel="noreferrer">MERGE</a> statement in Entity Framework.</p>
  
  <p>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.</p>
  
  <p>-Should there be a matching record in the db, I need to update the other fields in the db record.</p>
  
  <p>-Should there be no match, I need to insert the whole record.</p>
  
  <p>-Should there are any records in the db table that are not in the list I need to delete the records in the db.</p>
  
  <p>Here is the code I am struggling with so far.</p>
  
  <pre>
  <code>
  
              //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();
              }
  
  </code>
  </pre>
  
  <p>My question is: how do you elegantly achieve this?</p>