将TransactionScope与实体框架6一起使用

Mar*_*und 20 c# transactionscope savechanges dbcontext entity-framework-6

我无法理解的是,是否可以对上下文进行更改并在提交之前在同一事务中获取更改.

这就是我要找的:

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(); 
} 
Run Code Online (Sandbox Code Playgroud)

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

Kie*_*Chu 42

是的,它可以做,当你想要一个实体插入数据库并使用自动生成的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();
    }
} 
Run Code Online (Sandbox Code Playgroud)

因为您的问题也询问了工作模式,这是我的工作代码(使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

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();
Run Code Online (Sandbox Code Playgroud)

  • 问题由TransactionScope 回答Database.BeginTransaction。他是如何真正接受的呢?TransactionScope 有任何答案吗? (3认同)

Ste*_*ler 5

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

Item thisItem = context.Items.First();  
thisItem.Name = "Update name";    
Item thisUpdatedItem = context.Items.Local.Where(a=>a.Name == "Update name").First();
Run Code Online (Sandbox Code Playgroud)

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