我有一个充满数据的 DataTable 对象,并想将其保存到 SQL-DB (我不想运行 foreach 循环来执行插入),我的代码如下:
var dt = new DataTable();
//
// ... data loading to table dt
//
string sql = @"
INSERT INTO TB_Book (
BookID,
BookName
) SELECT
BookID,
BookName
FROM
@DataTable";
conn.execute(sql, new { DataTable = dt.AsTableValuedParameter("DataTable") });
Run Code Online (Sandbox Code Playgroud)
执行时,会抛出以下异常:
列、参数或变量@DataTable。: 找不到数据类型DataTable
我如何改进我的代码以使其发挥作用?
我还没有使用过 AsTableValuedParameter,但我确实使用在 dappers GIT 存储库中编写的单元测试来教自己任何简洁的东西。当我去那里调查你的问题时,我发现了以下内容:
看起来您会想要使用 AsTableValuedParameter() 而不提供“DataTable”类型。
以下是来自 StackExchange 的示例:
[Fact]
public void DataTableParameters()
{
try { connection.Execute("drop proc #DataTableParameters"); }
catch { }
try { connection.Execute("drop table #DataTableParameters"); }
catch { }
try { connection.Execute("drop type MyTVPType"); }
catch { }
connection.Execute("create type MyTVPType as table (id int)");
connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids");
var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } };
int count = connection.Query<int>("#DataTableParameters", new { ids = table.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).First();
count.IsEqualTo(3);
count = connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter("MyTVPType") }).First();
count.IsEqualTo(3);
try
{
connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter() }).First();
throw new InvalidOperationException();
}
catch (Exception ex)
{
ex.Message.Equals("The table type parameter 'ids' must have a valid type name.");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4501 次 |
| 最近记录: |