使用实体框架同步记录 [英] Synchronize Records using Entity Framework

查看:104
本文介绍了使用实体框架同步记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取SQL服务器的功能 MERGE 语句在实体框架中。

I am trying to get the functionality of SQL servers MERGE statement in Entity Framework.

在WCF服务中,我正在从客户端应用程序收到记录列表。
我想比较列表中的所有记录中的特定字段与数据库表。

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.

- 在db中有一个匹配的记录,I需要更新数据库记录中的其他字段。

-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.

- db表中是否有任何不在列表中的记录,我需要删除db中的记录。

-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.

您可以在 MSDN

这篇关于使用实体框架同步记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆