C# 在MongoDB中使用SqlBulkCopy
根据前面的问题,我试图从MongoDB数据库中执行C# 在MongoDB中使用SqlBulkCopy,c#,sql-server,mongodb,mongodb-.net-driver,C#,Sql Server,Mongodb,Mongodb .net Driver,根据前面的问题,我试图从MongoDB数据库中执行SqlBulkCopy,但我遇到了一个错误,无法找到我应该具有的列类型: 数据源中类型为ObjectId的给定值无法转换为指定目标列的nvarchar类型 其中,我的DataTable列DataType是MongoDB.Bson.ObjectId 要承载此值,Microsoft Sql Server中的类型应该是什么 我当前的代码: string connectionString = GetDestinationConnectionString
SqlBulkCopy
,但我遇到了一个错误,无法找到我应该具有的列类型:
数据源中类型为ObjectId
的给定值无法转换为指定目标列的nvarchar类型
其中,我的DataTable
列DataType
是MongoDB.Bson.ObjectId
要承载此值,Microsoft 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();
}
}
}
string connectionString=GetDestinationConnectionString();
var mongoCollection=GetSourceConnectionString();
var queryFind=Query.And(Query.NotExists(“sync”)、Query.NotIn(“challenge_guid”,new List(){“87558b59-73ee-4f10-add4-b9031551e395”});
var sourceData=mongoCollection.Find(queryFind.ToList();
DataTable dt=CollectionHelper.ConvertTo(sourceData);
使用(SqlConnection destinationConnection)=
新的SqlConnection(connectionString))
{
destinationConnection.Open();
//设置大容量复制对象。
//请注意,列在源中的位置
//数据读取器匹配中的列位置
//目标表,因此无需
//映射列。
使用(SqlBulkCopy)bulkCopy=
新SqlBulkCopy(目标连接))
{
bulkCopy.DestinationTableName=“JK_RawChallengeAnswers”;
尝试
{
//从源写入目标。
bulkCopy.WriteToServer(dt);
}
捕获(例外情况除外)
{
txtMsg.Text=ex.Message;
}
最后
{
//处理数据表。
dt.Dispose();
//密切联系
destinationConnection.Close();
}
}
}
来自:
ObjectId是一个12字节的BSON类型,使用以下内容构造:
- 一个4字节的时间戳
- 一个3字节的机器标识符
- 2字节的进程id,以及
- 一个3字节的计数器
无论如何,您的代码在任何重要的传输上都会耗尽内存,在内存中使用中间数据表拷贝不是一种可行的方法。并使用一个来及时迭代源代码。我会将
Mongo.Cursor
(它是查询的输出)转换为IDataReader
,而不创建新对象并实现它?这并不难,您只需要一个非常基本的IDataReader实现。请看更多示例:,