【发布时间】:2017-04-11 22:12:50
【问题描述】:
我是 MongoDB 新手,在学习了一些教程之后,我尝试从我的 SQL Server 数据库中读取数据并在 MongoDB 中使用 C# 和 Entity Framework 反转它们。
我在 MongoDB 网站上找到了这段代码:
async static void addDoc()
{
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
}
它按我的预期工作。所以,我做了这个:
using (var db = new Entities())
{
foreach (var trans in db.TRANSACTIONS)
{
try
{
var document = new BsonDocument
{
{ "ID", erog.ID.ToBson() },
{ "CUSTOMER" , new BsonDocument
{
{ "CSTID", trans.CUSTOMERS.CSTID.ToBson() },
{ "NAME", trans.CUSTOMERS.NAME.ToBson()},
{ "CITY", trans.CUSTOMERS.CITY.ToBson() },
{ "ZIP", trans.CUSTOMERS.ZIP.ToBson() },
{ "STATE", trans.CUSTOMERS.STATE.ToBson() },
}
},
{ "TRANSACTIONNUMBER", trans.TRANSACTIONNUMBER.ToBson() },
{ "TIMESTAMP", erog.TIMESTAMP.ToBson() },
{ "AMOUNT", erog.AMOUNT.ToBson() },
{ "PAYMENT", erog.PAYMENT.ToBson() },
};
var collection = _database.GetCollection<BsonDocument>("transactions");
collection.InsertOne(document);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
当我尝试执行此代码时,执行 var document = new BsonDocument {....}; 时出现错误错误是“无法将字符串值写入 bson 文档的根级别”。因此,如您所见,我尝试将 .ToBson() 放在值的末尾,但结果仍然相同。
唯一的区别是该值不是两个引号之间的字符串,而是我表中的真实值。
我怎样才能达到我的目标并在我的 MongoDB 数据库中创建和插入一个文档,从上面的代码开始?
【问题讨论】:
标签: c# mongodb entity-framework nosql