EF Code First DBContext 和事务 [英] EF Code First DBContext and Transactions

查看:35
本文介绍了EF Code First DBContext 和事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用 DBContext 实现事务的最佳方法是什么.尤其是

I would like know what is the best possible way to implement transactions with DBContext. In particular,

  1. 如果我更改多个实体,DbContext.SaveChanges 是否在内部实现事务?
  2. 如果我想多次调用DbContext.SaveChanges(相同的contxet/不同的contxets),如何实现事务?
  1. Does DbContext.SaveChanges implement transaction internall if i change multiple entities?
  2. If i want to call DbContext.SaveChanges multiple times(same contxet/different contxets), how transaction can be achieved?

推荐答案

  1. 是的.SaveChanges 在内部使用事务.
  2. 使用 TransactionScope 来包装多个对 SaveChanges
  3. 的调用
  1. Yes. SaveChanges uses transaction internally.
  2. Use TransactionScope to wrap multiple calls to SaveChanges

示例:

using(var scope = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    // Do something 
    context.SaveChanges();
    // Do something else
    context.SaveChanges();

    scope.Complete();
}

这篇关于EF Code First DBContext 和事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆