简体   繁体   English

Dapper-将int列表传递给存储过程

[英]Dapper - Pass list of int to stored procedure

My stored procedure SQL statemet is very simple. 我的存储过程SQL statemet非常简单。

Delete From TableName where ID IN (@id)

I want to pass list or array from C# code and wants to RETURN Number of rows deleted. 我想通过C#代码传递列表或数组,并希望返回删除的行数。

Below is my code, somehow I am not convinced and think this is not the right way to do. 下面是我的代码,不知为何我不认为这是正确的方法。 What is the efficient way of doing this? 有效的方法是什么?

using (SqlConnection connection = new SqlConnection(_connectionString))
{
    await connection.OpenAsync();

    DynamicParameters parameters = new DynamicParameters();

    foreach (var id in ids)
    {
        parameters.Add("@Id", id, DbType.Int32, ParameterDirection.Input);

        await connection.ExecuteAsync(
            ProcedureNames.DeleteRules,
            parameters,
            commandType: CommandType.StoredProcedure);
    }
}

Create a model to store the ids in the parameter. 创建一个模型以将id存储在参数中。 To get affected rows, take the result of the execute call. 要获取受影响的行,请获取execute调用的结果。

using (SqlConnection connection = new SqlConnection(_connectionString)) {
    await connection.OpenAsync();

    var affectedRows = await connection.ExecuteAsync(
            ProcedureNames.DeleteRules,
            new { id = ids.ToArray() }, //<-- Passing collection
            commandType: CommandType.StoredProcedure);
}

Another approach 另一种方法

using (SqlConnection connection = new SqlConnection(_connectionString)) {
    await connection.OpenAsync();

    var affectedRows = await connection.ExecuteAsync(
            ProcedureNames.DeleteRules,
            ids.Select(id => new { id = id }).ToArray(), //<-- Passing collection
            commandType: CommandType.StoredProcedure);
}

would execute the Statement multiple times. 将多次执行该语句。 Once for every object in the array list. 对数组列表中的每个对象一次。 It will still give you the total affected rows of executing all the statements. 它仍然会为您提供执行所有语句的总受影响行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM