2012-12-17 55 views
0

從先前的問題,我想從MongoDB數據庫做一個SqlBulkCopy,而我得到一個錯誤,並不能找到我應該有什麼樣的列類型:使用與SqlBulkCopy的MongoDB的

來自數據源的ObjectId類型的給定值無法轉換爲指定目標列的nvarchar類型。

enter image description here

凡我DataTableDataTypeMongoDB.Bson.ObjectId

什麼應該是微軟Sql Server中的類型來承載這個值?

我當前的代碼:

string connectionString = GetDestinationConnectionString(); 
var mongoCollection = GetSourceConnectionString(); 

var queryFind = Query.And(Query.NotExists("sync"), Query.NotIn("challenge_guid", new List<MongoDB.Bson.BsonValue>() { "87558b59-73ee-4f10-add4-b9031551e395" })); 
var sourceData = mongoCollection.Find(queryFind).ToList(); 

DataTable dt = CollectionHelper.ConvertTo<MongoAnswerDoc>(sourceData); 

using (SqlConnection destinationConnection = 
      new SqlConnection(connectionString)) 
{ 
    destinationConnection.Open(); 

    // Set up the bulk copy object. 
    // Note that the column positions in the source 
    // data reader match the column positions in 
    // the destination table so there is no need to 
    // map columns. 
    using (SqlBulkCopy bulkCopy = 
       new SqlBulkCopy(destinationConnection)) 
    { 
     bulkCopy.DestinationTableName = "JK_RawChallengeAnswers"; 

     try 
     { 
      // Write from the source to the destination. 
      bulkCopy.WriteToServer(dt); 
     } 
     catch (Exception ex) 
     { 
      txtMsg.Text = ex.Message; 
     } 
     finally 
     { 
      // Dispose of the DataTable. 
      dt.Dispose(); 
      // close connection 
      destinationConnection.Close(); 
     } 
    } 
} 

回答

1

Mongo spec

的ObjectId是一個12字節的BSON型,構建使用:

  • 一個4字節的時間戳,
  • 一個3字節的機器標識符,
  • 一個2字節的進程ID,和
  • 一個3字節的計數器。

所以,你會需要一個BINARY(12)類型列,它的SQL Map。

無論如何,你的代碼在任何意義上的傳輸都會耗盡內存,使用中間DataTable內存拷貝是不行的。 EnableStreaming並使用IDataReader即時迭代源代碼。

+0

我想通過將'Mongo.Cursor'(巫婆是查詢的輸出)轉換爲'IDataReader'而不創建新對象並實現它? – balexandre

+0

不難,你只需要一個非常基本的IDataReader實現。看看http://blogs.microsoft.co.il/blogs/aviwortzel/archive/2008/05/06/implementing-sqlbulkcopy-in-linq-to-sql.aspx –

+1

更多例子:http:// www .developerfusion.com/article/122498/using-sqlbulkcopy-for-high-performance-inserts /,http://www.csvreader.com/posts/generic_list_datareader.php –