0

只需掌握实体框架,我就可以保存、添加、删除等单个实体,如下所示:

db.Entry(client).State = EntityState.Modified;
db.SaveChanges();

我的问题是,如果我想更改几条记录,我应该如何执行此操作,例如,我想选择所有类型为“新”的作业并将类型设置为“完成”。我可以使用 Linq 轻松选择所有作业,但我是否必须循环、更改它们、将状态设置为已修改、保存更改、下一个等?我敢肯定,有一种我只是不知道或设法找到的简单方法。

4

2 回答 2

0

Yes, you would have to loop through each object, but you don't have to save changes after each one. You can save changes after all the changes have been made and update in a single go. Unless there is some reason you need to save before editing the next record.

However, if you have a simple operation like that, you can also just issue a SQL statement to do it.

context.Table.SqlQuery("UPDATE table set column = 1 where column2 = 3");

Obviously, that more or less bypasses the object graph, but for a simple batch statement there's nothing wrong with doing that.

于 2012-10-10T14:27:45.653 回答
0

你确定你需要设置EntityState吗?SaveChanges 将在保存前检测Changes。您不能根据请求一次更新多条记录,但您可以循环,更新值并在循环后调用保存更改。这将导致与数据库的 1 个连接,您的所有更新记录将立即保存在该数据库中。

于 2012-10-10T14:20:46.270 回答