0

I have a doubt, the _context.Database.ExecuteSqlCommandAsync method autocommit a transaction or not.

My code looks like this:

using (DatabaseContext _db = new DatabaseContext())
{
     using(var _transaction = _db.Database.BeginTransaction())
     {
          try
          {
              await _db.Database.ExecuteSqlCommandAsync(query, paramsList);
              _transaction.Commit();
          }
          catch(Exception ex)
          {
              _transaction.Rollback();
              throw;
          }
     }
}

I assume that method doesn't auto commit the transaction, so I decided to commit it manually.

Is a good practice?, or is not necessary doing this?

4

2 回答 2

1

不,您不需要提交 ExecuteSqlCommandAsync,但由于这会直接写入数据库,因此 EF 跟踪的实体可能会过期。

为了解决这个问题,只需处理并重新制作上下文:

using (DatabaseContext _db = new DatabaseContext())
{
   await _db.Database.ExecuteSqlCommandAsync(query, paramsList);
}
using (DatabaseContext _db = new DatabaseContext())
{
   var itemsJustInserted = _db.Items.ToList(); //should have your modified items
}
于 2017-01-24T16:07:01.377 回答
0

不,你不需要..

ExecuteSqlCommandAsync(字符串,CancellationToken,对象[])

备注 如果没有现有的本地事务,将使用新事务来执行命令。

https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.database.executesqlcommandasync?view=entity-framework-6.2.0

于 2019-12-10T03:21:26.683 回答