您好我正在尝试插入mongoDB 2对象。 当我插入1个对象时,它工作正常,
private void Query<TO>(TO o)
{
const string connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<TO>(o.GetType().Name + "s");
collection.Insert(o);
}
但是当我尝试插入2个对象时,BSON驱动程序发生错误
private void Query<TO, TK, TV>(TO o, Dictionary<TK, TV> ExtraFields)
{
const string connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<Object[]>(o.GetType().Name + "s");
collection.Insert(new List<object>
{
o,
ExtraFields
});
}
我得到的错误是
{“Serializer EnumerableSerializer预期序列化 不是类型ArraySerializationOptions的选项 DocumentSerializationOptions。“}
由于
答案 0 :(得分:0)
您的集合类型必须是类,不能是数组或集合。不确定您是否尝试将“2个对象”视为一个文档或将它们作为单独的项目插入。您需要创建一个类来保存它们或者自己构建BsonDocument并以这种方式存储它们。我认为你不能像你一样使用泛型。 像这样:
public class ObjectWithExtraFields {
public Type1 O { get; set; }
public Dictionary<string, Type2> ExtraFields { get; set; }
}
var collection = database.GetCollection<ObjectWithExtraFields>(o.GetType().Name + "s");
collection.Insert(new ObjectWithExtraFields {
O = o,
ExtraFields = ExtraFields
});