使用dapper时,我想将整个Datatable插入DB(Sql Server 2012),我的代码如下:
using(var conn = CreateConnection()) {
conn.Open();
using(var tran = cn.BeginTransaction()) {
try {
DataTable dt = new DataTable();
//
// ... some data loaded to dt;
//
// drop type before creation to make sure type name is free to use
try { conn.Execute("DROP TYPE tmpType", null, tran); } catch { }
try { conn.Execute("CREATE TYPE tmpType AS TABLE (id [int] NULL)", null, tran); } catch { }
dt.SetTypeName("tmpType");
conn.Execute("INSERT INTO table_Sample (id) SELECT id FROM @DataTable", new { DataTable = dt.AsTableValuedParameter() }, tran);
try { conn.Execute("DROP TYPE tmpType", null, tran); } catch { }
tran.Commit(); // throws exception here, transaction already completed
} catch {
tran.Rollback();
throw;
}
}
}
因为第一个" DROP TYPE tmpType"由于没有tmpType实际存在,语句将失败,当我运行上面的代码时,它会抛出异常:
此SqlTransaction已完成;它不再可用了。
如何改进我的代码以使其正常工作(并避免潜在的类型名称冲突)?