Dapper 也可以使用 数组参数
Dapper 调用存储过程 :单个参数
static void Main(string[] args)
{
var connection = new SqlConnection("Data Source=.;Initial Catalog=Datamip;Integrated Security=True;MultipleActiveResultSets=True");
var info = connection.Query<Users>("sp_GetUsers", new { id = 5 },
commandType: CommandType.StoredProcedure);
}
Dapper 调用存储过程 :数组参数
需要使用 Sql Server 的自定义类型 : dbo.IDList
CREATE TYPE dbo.IDList
AS TABLE
(
ID INT
);
GO
c# code
public static List<WorkLog> QueryWithTVP()
{
int[] idList = new int[] { 1, 2 };
var results = new List<WorkLog>();
try
{
var typeIdsParameter = new List<SqlDataRecord>();
// TypeID 数组参数对应的字段
var myMetaData = new SqlMetaData[] { new SqlMetaData("TypeID", SqlDbType.Int) };
foreach (var num in idList)
{
// Create a new record, i.e. row.
var record = new SqlDataRecord(myMetaData);
// Set the 1st colunm, i.e., position 0 with the correcponding value:
record.SetInt32(0, num);
// Add the new row to the table rows array:
typeIdsParameter.Add(record);
}
using (IDbConnection conn = new SqlConnection(DBConfig.ConnectionString))
{
conn.Open();
//调用存储过程,IDList: 自定义类型
results = conn.Query<WorkLog>("dbo.GetWorkLog_ByTypeIds",
new TableValueParameter("@TypeIds", "IDList", typeIdsParameter)
, commandType: CommandType.StoredProcedure).ToList();
}
}
catch (Exception)
{
throw;
}
return results;
}