实体框架如何处理事务?
当您在上下文中调用 SaveChanges 时,实体框架是否使用事务?有没有办法完全关闭交易,或者让某个实体选择退出交易?
AdventureWorksEntities db = new AdventureWorksEntities();
Product p1 = new Product();
// ...
Product p2 = new Product();
// set invalid data
db.Products.AddObject(p1);
db.Products.AddObject(p2);
// what happens when I call this - does it roll back everything?
// can i tell p2 not to participate in the transaction?
db.SaveChanges();
Does Entity Framework use a transaction for when you call SaveChanges on your context? Is there any way to turn off transactions completely, or have a certain entity opt out of a transaction?
AdventureWorksEntities db = new AdventureWorksEntities();
Product p1 = new Product();
// ...
Product p2 = new Product();
// set invalid data
db.Products.AddObject(p1);
db.Products.AddObject(p2);
// what happens when I call this - does it roll back everything?
// can i tell p2 not to participate in the transaction?
db.SaveChanges();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是,如果交易尚不存在,EF4 将创建一个新交易。请参阅
http://msdn.microsoft.com/en-us/library/bb896325。 ASPX
不,没有办法使单个实体免于交易。
不确定你的第三个问题 - 关于是否可以完全关闭交易,但我猜不是基于上面的摘录。
我知道这不是您想听到的答案,但如果您希望无论 P1 是否成功都保存 P2,您需要将 P2 保存到不同的对象上下文中。
Yes, EF4 will create a new transaction if one does not already exist. See
http://msdn.microsoft.com/en-us/library/bb896325.aspx
No, there is no way to exempt a single entity from the transaction.
Not sure about your third question - about whether you can turn off transactions completely, but I'm guessing not based on the above excerpt.
I know this isn't the answer you wanted to hear, but if you want P2 to save regardless of whether P1 succeeds, you would need to save P2 into a different object context.
关于关闭交易的最新问题。
尝试使用 Suppress TransactionScopeOption 创建 TransactionScope 以关闭事务完全针对代码块。查看此线程 了解更多信息。
Concerning the latest question about turning the transactions off.
Try to create TransactionScope with Suppress TransactionScopeOption to turn off the transactions completely for the code block. Take a look at this thread for some more information.