0

在 Code-First Entity Framework 中,有没有办法修改事务行为,使其不会丢弃所有更改,而是将所有更改保持到故障点?

例如:

foreach {var objectToSave in ArrayOfEntityObjects)
{
     MyContext.Insert(objectToSave);
}
try
{
     MyContext.SaveChanges();
}
catch (Exception x)
{
    //handling code
}

在上面的示例中,假设数组是一个包含 100 个对象的数组,并且在第 50 项上发生了错误,我想保留那些成功的对象,至少到失败点为止。知道我们在 foreach 循环的每次迭代期间执行 MyContext.SaveChanges() 命令来执行此操作,但我们希望在一次提交中提交到数据库的性能提升(我们的理解是 EF 一次发送所有命令对于事务,通过单个连接,因此仅使用一次往返)。

4

1 回答 1

0

No, there is no way to do this automatically. EF commits all changes in a single transaction, which means it's an all or nothing thing.

If you want this behavior, then you must save changes after each and every record you add.

The reason is that EF doesn't know what constitutes a "transaction" in your data. It might be one row, or it might be several rows in several tables. EF doesn't even try to understand what your transactional requirements might be. You have to do it manually if you want it.

于 2013-09-24T00:42:59.587 回答