5 c# sql-server entity-framework
我试图在Entity Framework中获得SQL服务器MERGE语句的功能.
在WCF服务中,我收到来自客户端应用程序的记录列表.我想比较列表中所有记录中的特定字段与数据库表.
- 如果db中有匹配的记录,我需要更新db记录中的其他字段.
- 如果没有匹配,我需要插入整个记录.
- 如果db表中有任何记录不在列表中,我需要删除db中的记录.
这是我到目前为止正在努力的代码.
//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();
}
我的问题是:你如何优雅地实现这一目标?
| 归档时间: |
|
| 查看次数: |
5296 次 |
| 最近记录: |