0

您好我正在尝试插入 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。"}

谢谢

4

1 回答 1

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
});
于 2014-05-08T02:45:11.057 回答