开发者

Synchronize Records using Entity Framework

开发者 https://www.devze.com 2023-01-19 18:19 出处:网络
I am trying to get the functionality of SQL servers MERGE statement in Entity 开发者_Go百科Framework.

I am trying to get the functionality of SQL servers MERGE statement in Entity 开发者_Go百科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?


I would make use of the Sync Framework for that task. It seems perfectly fit for that kind of scenario.

You can find a lot of information on the subject on MSDN

0

精彩评论

暂无评论...
验证码 换一张
取 消