Skip to content

Execution context

sdrapkin edited this page Apr 11, 2017 · 1 revision

TinyORM defaults to using sp_executesql for all queries.
This causes all statements to run within the execution context of sp_executesql sproc. Some rare scenarios, however, may call for the execution context to be preserved across multiple TinyORM queries. The following would not work under default settings:

using (var ts = DbContext.CreateTransactionScope())
{
	await db.QueryAsync("CREATE TABLE #Temp (Id INT PRIMARY KEY CLUSTERED);");
	await db.QueryAsync(QB.Insert(new { Id = 1 }, tableName: "#Temp")); // exception: "Invalid object name '#Temp'
	(await db.QueryAsync("SELECT * FROM #Temp;")).Dump();
	ts.Complete();
}

Each TinyORM query runs in its own execution context by default, so the 2nd query does not see the temporary table created by the 1st query. One way to preserve the execution context is to run raw-TSQL instead of sp_executesql:

using (var ts = DbContext.CreateTransactionScope())
{
	await db.QueryAsync("CREATE TABLE #Temp (Id INT PRIMARY KEY CLUSTERED);", sqlTextOnly: true); // preserves context
	await db.QueryAsync(QB.Insert(new { Id = 1 }, tableName: "#Temp"));
	(await db.QueryAsync("SELECT * FROM #Temp;")).Dump();
	ts.Complete();
}