简体   繁体   English

EF Code First DBContext和Transactions

[英]EF Code First DBContext and Transactions

I would like know what is the best possible way to implement transactions with DBContext . 我想知道用DBContext实现事务的最佳方法是什么。 In particular, 特别是,

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

Example: 例:

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

    scope.Complete();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM