将TransactionScope与实体框架6

本文关键字:框架 实体 TransactionScope | 更新日期: 2023-09-27 18:25:33

我不明白的是,是否可以对上下文进行更改,并在提交前在同一事务中获得更改。

这就是我想要的:

using (var scope = new TransactionScope(TransactionScopeOption.Required)) 
{ 
    using (var context = new DbContext()) 
    { 
        //first I want to update an item in the context, not to the db
        Item thisItem = context.Items.First();
        thisItem.Name = "Update name";
        context.SaveChanges(); //Save change to this context
        //then I want to do a query on the updated item on the current context, not against the db
        Item thisUpdatedItem = context.Items.Where(a=>a.Name == "Update name").First();
        //do some more query
    } 
    //First here I want it to commit all the changes in the current context to the db
    scope.Complete(); 
} 

有人能帮我理解并向我展示工作模式吗?

将TransactionScope与实体框架6

是的,当您想将实体插入数据库并使用自动生成的id进行下一次插入或更新时,可以这样做,这非常有用

using (var context = new DbContext())     
{ 
    using (var transaction = context.Database.BeginTransaction()) {
        var item = new Item();
        context.Items.Insert(item);
        context.SaveChanges(); // temporary insert to db to get back the auto-generated id
        // do some other things
        var otherItem = context.OtherItems.First();
        // use the inserted id
        otherItem.Message = $"You just insert item with id = {item.Id} to database";
        transaction.Commit();
    }
} 

因为您的问题还询问了工作模式,所以这里是我的工作代码(使用FluentApi、DbContext&Transaction)。我和你有同样的问题:)。希望它能帮助你

public class FluentUnitOfWork : IDisposable
{
    private DbContext Context { get; }
    private DbContextTransaction Transaction { get; set; }
    public FluentUnitOfWork(DbContext context)
    {
        Context = context;
    }
    public FluentUnitOfWork BeginTransaction()
    {
        Transaction = Context.Database.BeginTransaction();
        return this;
    }
    public FluentUnitOfWork DoInsert<TEntity>(TEntity entity) where TEntity : class
    {
        Context.Set<TEntity>().Add(entity);
        return this;
    }
    public FluentUnitOfWork DoInsert<TEntity>(TEntity entity, out TEntity inserted) where TEntity : class
    {
        inserted = Context.Set<TEntity>().Add(entity);
        return this;
    }
    public FluentUnitOfWork DoUpdate<TEntity>(TEntity entity) where TEntity : class
    {
        Context.Entry(entity).State = EntityState.Modified;
        return this;
    }
    public FluentUnitOfWork SaveAndContinue()
    {
        try
        {
            Context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            // add your exception handling code here
        }
        return this;
    }
    public bool EndTransaction()
    {
        try
        {
            Context.SaveChanges();
            Transaction.Commit();
        }
        catch (DbEntityValidationException dbEx)
        {
            // add your exception handling code here
        }
        return true;
    }
    public void RollBack()
    {
        Transaction.Rollback();
        Dispose();
    }
    public void Dispose()
    {
        Transaction?.Dispose();
        Context?.Dispose();
    }
}

示例用法:

var status = BeginTransaction()
                // First Part
                .DoInsert(entity1)
                .DoInsert(entity2)
                .DoInsert(entity3)
                .DoInsert(entity4)
                .SaveAndContinue()
                // Second Part
                .DoInsert(statusMessage.SetPropertyValue(message => message.Message, $"Just got new message {entity1.Name}"))
            .EndTransaction();

如果您想确保只查询上下文的本地内容,可以使用"本地"集合:

Item thisItem = context.Items.First();  
thisItem.Name = "Update name";    
Item thisUpdatedItem = context.Items.Local.Where(a=>a.Name == "Update name").First();

这将只查询上下文的内存中数据,不会命中数据库
只要通过添加对象或从数据库加载对象,在上下文中实现对象,"本地"数据就会出现,即不需要调用SaveChanges()
SaveChanges()将把上下文的内容写入数据库。

根据我的经验,创建上下文是不必要的,我喜欢尽可能简化,所以如果您需要在回滚时命中代码,请用try-catch包围事务。

try
{
   using (var scope = new TransactionScope(TransactionScopeOption.Required))
   {
          ...do stuff
          scope.Complete();
   }
}
catch (Exception)
{
  ...do stuff
}