Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
omatrot opened this issue Dec 7, 2021 · 0 comments

Comments

@omatrot
Copy link

omatrot commented Dec 7, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant