带有表值参数的 Dapper 动态参数 [英] Dapper Dynamic Parameters with Table Valued Parameters

查看:28
本文介绍了带有表值参数的 Dapper 动态参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个通用方法,它可以在运行时从类中读取参数名称和值,并为 Dapper 查询执行创建参数集合.意识到直到所有参数都是输入类型它运行良好,但是如果我必须添加 Output/ReturnValue 类型参数,那么我需要使用 DynamicParameters,否则我无法获取Output/ReturnValue 参数的值

I was trying to create a generic method, which can read the parameters name and value from a class at Runtime and create parameter collection for Dapper query execution. Realized that till the point all parameters are Input type it works well, but if I have to add an Output / ReturnValue type parameters, then I need to work with DynamicParameters, else I cannot fetch the value of Output / ReturnValue parameters

SP 有以下参数:

PersonList - TableValued - Input
TestOutput - Int - Output

我无法使以下代码工作:

I am not able to make following piece of code work:

var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("PersonList", <DataTable PersonList>);
dynamicParameters.Add("TestOutput", 0, Dbtype.Int32, ParameterDirection.Output);

例外是:

System.Data.SqlClient.SqlException:传入的表格数据流 (TDS)远程过程调用 (RPC) 协议流不正确.参数 1("@PersonList"): 数据类型 0x62 (sql_variant) 的类型无效 -特定的元数据.

System.Data.SqlClient.SqlException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 1 ("@PersonList"): Data type 0x62 (sql_variant) has an invalid type for type- specific metadata.

据我所知,问题是没有可用于将 TVP 添加到动态参数的有效 DbType,因为我没有使用 SqlDbType,因此 DbType 中没有替代 SqlDbType.Structured.

Issue as I can understand is there's no valid DbType available for adding a TVP to the Dynamic Parameters, since I am not using the SqlDbType, so there's no replacement for SqlDbType.Structured in the DbType.

解决问题的任何指针或解决方法

Any pointer or workaround to resolve the issue

推荐答案

首先在Database中创建一个User Defined Table类型

First create a User Defined Table type in Database

CREATE TYPE udtt_PersonList AS TABLE 
(
    ...
)
GO

在你的代码中

var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("@PersonList", PersonList.AsTableValuedParameter("[dbo].[udtt_PersonList]"));
dynamicParameters.Add("TestOutput", 0, Dbtype.Int32, ParameterDirection.Output);

这篇关于带有表值参数的 Dapper 动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆