2012-12-17 56 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 –