How to rollback a transaction in Entity Framework(如何在实体框架中回滚事务)
问题描述
string[] usersToAdd = new string[] { "asd", "asdert", "gasdff6" };
using (Entities context = new Entities())
{
foreach (string user in usersToAdd)
{
context.AddToUsers(new User { Name = user });
}
try
{
context.SaveChanges(); //Exception thrown: user 'gasdff6' already exist.
}
catch (Exception e)
{
//Roll back all changes including the two previous users.
}
或者这可能是自动完成的,这意味着如果发生错误,则会取消所有更改的提交更改.是吗?
Or maybe this is done automatically, meaning that if error occurs, committing changes are canceled for all the changes. is it?
推荐答案
OK
我创建了一个示例应用程序,就像我在数据库中检查的问题和后记中的示例一样,没有添加任何用户.
I created a sample a application like the example from the the question and afterwords I checked in the DB and no users were added.
结论:ObjectContext.SaveChange 它自动是一个事务.
注意:如果执行 sprocs 等,我相信交易是需要的.
Note: I believe transactions will be needed if executing sprocs etc.
这篇关于如何在实体框架中回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在实体框架中回滚事务


基础教程推荐
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 创建属性设置器委托 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01