在Dapper ..net c#中创建临时表

dpiehjr4  于 2023-03-13  发布在  .NET
关注(0)|答案(1)|浏览(329)

我尝试使用Dapper创建一个#临时表,但没有成功。我没有收到任何SQL异常或错误,连接打开了,但最终结果是“-1”,没有创建临时表。有人知道我哪里出错了吗?
谢谢

public abstract class DapperBaseRepository : IDisposable
{
    private readonly IDbConnection _dbConnection;

    protected DapperBaseRepository()
    {
        _dbConnection = new SqlConnection(configuration.GetConnectionString("DefaultConnection"));
    }

    public async Task<int> CreateTempTable()
    {
        string mappingTable = "[dbo].[#IngredientSubstitutionUpload]";
        
        var query = @$"
            CREATE TABLE {mappingTable}(
                Row int NOT NULL,
                OriginalIngredient nvarchar(255) NOT NULL,
                OriginalSupplierCode nvarchar(255) NOT NULL,
                ReplacementIngredient nvarchar(255) NOT NULL,
                ReplacementSupplierCode nvarchar(255) NOT NULL)
        ";
    
        await _dbConnection.ExecuteAsync(query); // return -1
        
        
        // When attempting to insert here error is thrown: - Invalid object name '#IngredientSubstitutionUpload'.
        
        // Insert into temporary table 
        await _dbConnection.ExecuteAsync(
            $"INSERT INTO {mappingTable} VALUES (@row, @originalIngredient, @originalSupplierCode, @replacementIngredient, @replacementSupplierCode)",
            substitutions.Select((x, idx) => new
            {
                row = idx,
                originalIngredient = x.OriginalIngredient,
                originalSupplierCode = x.OriginalSupplierCode,
                replacementIngredient = x.ReplacementIngredient,
                replacementSupplierCode = x.ReplacementSupplierCode
            }));

    }
    
    public void Dispose()
    {
        _dbConnection.Dispose();
    }
}
oogrdqng

oogrdqng1#

你需要在调用ExecuteAsyc语句之前显式地打开连接,否则Dapper会在每个ExecuteAsync语句调用一个单独的会话后自动关闭连接(临时表将无法继续使用)。
样品取自https://www.learndapper.com/misc/temporary-table

using (var connection = new SqlConnection(connectionString))
{
    await conn.Open();
    
    connection.Execute(@"CREATE TABLE #tmpOrder(orderId int);");
    connection.Execute(@"INSERT INTO #tmpOrder(orderId) VALUES (1);");
    
    return connection.Query<int>(@"SELECT * FROM #tmpOrder;");
}

相关问题