EF Core的SaveChanges方法本身就是事务
但是如果多个SaveChanges方法提交,则需用IDbContextTransaction
using (EFCoreContext context = new EFCoreContext())
{
IDbContextTransaction tran = null;
try
{
tran = context.Database.BeginTransaction();
context.UserInfo.Add(new UserInfo()
{
Name = "haha11",
Age = 19
});
context.SaveChanges();
context.UserInfo.Add(new UserInfo()
{
Name = "haha22",
Age = 19
});
context.SaveChanges();
tran.Commit();
}
catch (Exception ex)
{
if (tran != null)
tran.Rollback();
Console.WriteLine(ex.Message);
}
finally
{
tran.Dispose();
}
}
如果是多个Context,即分布式事务,则需用TransactionScope
using (EFCoreMigrationContext context1 = new EFCoreMigrationContext())
using (EFCoreMigrationContext context2 = new EFCoreMigrationContext())
{
using (TransactionScope transactionScope = new TransactionScope())
{
try
{
context1.UserInfo.Add(new UserInfo()
{
Name = "hehe11",
Age = 20
});
context1.SaveChanges();
context2.UserInfo.Add(new UserInfo()
{
Name = "hehe22",
Age = 20
});
context2.SaveChanges();
transactionScope.Complete();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
今天的文章【EFCore】EF Core事务提交,分布式事务分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/9967.html