Dapper use Table Value Parameter in C# (Sql Server 数组参数)
Posted leestone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Dapper use Table Value Parameter in C# (Sql Server 数组参数)相关的知识,希望对你有一定的参考价值。
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;
}
以上是关于Dapper use Table Value Parameter in C# (Sql Server 数组参数)的主要内容,如果未能解决你的问题,请参考以下文章
csharp: mappings using Dapper-Extensions+Dapper.net.
Merge Into ----using table to keep properties contents
Mysql: Invalid use of null value
Dapper: How to get return value ( output value) by call stored procedure