Search code examples
c#sqlsql-serverdappertransactionscope

Why is SQL context_info lost on second database call?


Even though I'm using the same SQL connection, if I assign the context_info in one call, I lose it in the next call.

Why is this and how can I ensure context_info is retained for the other call?

See below for my minimal repro:

using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

await using var connection = new SqlConnection(_configuration.ConnectionString);

var parameters = new
{
    ContextInfo = Guid.NewGuid().ToByteArray();
};

// This assigns correctly
var first = await connection.QuerySingleAsync($@"
    SET CONTEXT_INFO @{nameof(parameters.ContextInfo)};

    SELECT CONTEXT_INFO();",
    parameters);

// This is null
var second = await connection.QuerySingleAsync("SELECT CONTEXT_INFO();");

scope.Complete();

Solution

  • You're not opening the connection yourself. That means Dapper will take care of opening and closing the connection on each call. Which means the second call is on a different (logical) connection.

    Try adding connection.Open(); (or, of course, OpenAsync if you prefer) before any Dapper calls