我无法理解的是,是否可以对上下文进行更改并在提交之前在同一事务中获取更改.
这就是我要找的:
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(); }
有人能帮我理解并向我展示一种工作模式吗?
是的,它可以做,当你想要一个实体插入数据库并使用自动生成的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 entity) where TEntity : class { Context.Set ().Add(entity); return this; } public FluentUnitOfWork DoInsert (TEntity entity, out TEntity inserted) where TEntity : class { inserted = Context.Set ().Add(entity); return this; } public FluentUnitOfWork DoUpdate (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();