EF Code First DBContext and Transactions
问题描述:
我想知道用DBContext
实现交易的最佳方式是什么。特别是,EF Code First DBContext and Transactions
- 是否
DbContext.SaveChanges
实现交易内部如果我改变多个实体? - 如果我想多次拨打
DbContext.SaveChanges
(同一个contxet /不同的contxets),如何实现交易?
答
- 是的。
SaveChanges
内部使用事务。 - 使用
TransactionScope
包裹多次调用SaveChanges
例子:
using(var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
// Do something
context.SaveChanges();
// Do something else
context.SaveChanges();
scope.Complete();
}
一定要使用SQL 2008或更高版本的数据库(或有MSDTC服务的客户端上运行)。以前的版本会将事务升级为第二个'SaveChanges'上的分布式事务。这是由于'DbContext'如何在内部处理其连接的打开和关闭。 – Lukazoid 2012-01-19 15:51:46
是否可以从第一次保存更改中获取身份?我总是看到Id = 0. – JarrettV 2012-01-24 17:11:03
@JarrettV - 我认为你的问题是因为IsolationLevel设置。降低它可能会有帮助... – Sunny 2012-03-12 17:00:39