Skip to content

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

@omatrot

Description

@omatrot

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.");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions