Search code examples
c#entity-frameworkrawsql

Database.ExecuteSqlCommandAsync autocommit transaction?


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?


Solution

  • No, you don't need to commit an ExecuteSqlCommandAsync, but since this directly writes the database, the entities tracked by EF might be left out of date.

    To counter this, just dispose and remake the context:

    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
    }