如何用ApplyCurrentValues更新整个实体列表?

时间:2013-01-29 01:59:42

标签: c# sql entity-framework

好的,

这是我如何更新单个对象:

public void UpdateRespondent(Respondent changed)
{
    var respondent = db.Respondents.FirstOrDefault(r => r.RespondentId == changed.RespondentId);

    db.Respondents.ApplyCurrentValues(changed);
    db.SaveChanges();
}

这将调用1次选择和1次更新(如果有更改)。

现在,如果我有一个List<Respondent>,其中有数百个,我该怎么做,在循环中对每个调用UpdateRespondent(已更改)?这将产生数百* 2个sql语句。

或者有更有效的方法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

EF不支持批量更新。您可以查看使用EntityFramework扩展库 - 我见过其他成功使用它的人:

https://github.com/loresoft/EntityFramework.Extended

上面链接的代码片段:

//update all tasks with status of 1 to status of 2
context.Tasks.Update(
    t => t.StatusId == 1, 
    t2 => new Task {StatusId = 2});

//example of using an IQueryable as the filter for the update
var users = context.Users.Where(u => u.FirstName == "firstname");
context.Users.Update(users, u => new User {FirstName = "newfirstname"});

或者,您可以直接使用ADO.Net并调用存储的程序。

祝你好运。

相关问题