TrackableEntities / trackable-entities

N-Tier Support for Entity Framework with WCF or ASP.NET Web API
http://trackableentities.github.io
MIT License
120 stars 36 forks source link

What about a transaction scope with SaveChangesAsync() and Command.ExecuteScalarAsync() ? #239

Open omatrot opened 2 years ago

omatrot commented 2 years ago

Hi,

I'd like to use SaveChanges within a transaction. I suppose it is supported. Now, what I reall need is to call a stored procedure after SaveChanges within the scope of that transaction.

What I've found out so far is that the SQL connection is closed after the call to SaveChanges... Am I right ?

Can I do something like the following in a transaction and reverse what is done within SaveChanges if the stored procedure thows or the result is not the one expected ?

// Apply the incoming changes to the context
_DbContext.ApplyChanges(vehicle);

// Persist the changes to the database
await _DbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

// Set the entity graph to unchanged
_DbContext.AcceptChanges(vehicle);

using (var cmd = _DbContext.Database.GetDbConnection().CreateCommand())
{
    cmd.CommandTimeout = 10;
    cmd.CommandText =
        "DECLARE    @return_value int " +
        "EXEC @return_value = [SafeProtect].[TryRegisterDati] @companyId = " + vehicle.CompanyId + ", @vehiculeId = " + vehicle.VehiculeId +
        " SELECT    @return_value";
    var result = await cmd.ExecuteScalarAsync();
    if (result.ToString() != "1")
    {
        throw new InvalidOperationException("No more licence available.");
    }
}