2017-01-13 1 views
0

내가 데이터로 채워진 DataTable 개체를 가지고 있고, (내가 삽입을 할 수있는 foreach 루프를 실행하지 않으) SQL-DB에 저장하려면, 나는 다음과 같은 코드 :dapper를 사용하여 전체 DataTable을 저장하는 방법은 무엇입니까?

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") }); 

때 페이지가 실행될 때 다음 예외를 throw합니다.

열, 매개 변수 또는 변수 @DataTable. : 데이터 형식을 찾을 수 없습니다. DataTable

이 코드를 개선하려면 어떻게해야합니까?

답변

2

아직 AsTableValuedParameter로 작업하지는 않았지만 DAPER GIT Repository에서 작성된 Unit 테스트를 사용하여 더 멋진 것을 가르쳐줍니다. 귀하가 제공 한 "DataTable을"형식없이 AsTableValuedParameter()를 사용하기를 원할 것 같은

https://github.com/StackExchange/dapper-dot-net/blob/61e965eed900355e0dbd27771d6469248d798293/Dapper.Tests/Tests.Parameters.cs#L251

것 같습니다 : 내가 질문을 조사하기 위해 거기에 갔을 때 나는 다음과 같은 위치.

[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."); 
    } 
} 
: 여기

는 StackExchange의 예는
관련 문제