Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用C从MongoDB获取继承的实例#_C#_Mongodb_Mongodb .net Driver - Fatal编程技术网

C# 使用C从MongoDB获取继承的实例#

C# 使用C从MongoDB获取继承的实例#,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我使用的是官方的MongoDb C#驱动程序 我的场景:我将对象存储到MongoDb中。所有对象都是从同一根类继承的类的实例。 在设计时,我不知道所有可以存储的类(即它们可以插入),因此我需要某种方法来告诉序列化程序/驱动程序如何将类映射到文档(文档中的描述符) 有人有什么想法吗?看看驱动程序序列化文档。只要对象的实际类型与标称类型不同,官方C#驱动程序就会编写一个“_t”鉴别器值。例如: MyRootClass obj = new MyDerivedClass(); collection.In

我使用的是官方的MongoDb C#驱动程序

我的场景:我将对象存储到MongoDb中。所有对象都是从同一根类继承的类的实例。 在设计时,我不知道所有可以存储的类(即它们可以插入),因此我需要某种方法来告诉序列化程序/驱动程序如何将类映射到文档(文档中的描述符)


有人有什么想法吗?

看看驱动程序序列化文档。

只要对象的实际类型与标称类型不同,官方C#驱动程序就会编写一个“_t”鉴别器值。例如:

MyRootClass obj = new MyDerivedClass();
collection.Insert(obj);
Insert语句也可以编写为:

collection.Insert<MyRootClass>(obj);

从技术上讲,序列化不使用反射;它是元数据驱动的。反射只用于构造类映射一次,但之后直接使用类映射而不进行反射,开销相当低。

我编写了一个帮助器类,改进了Robert Stam的优秀答案,并允许使用与静态BsonClassMap.RegisterClassMap()方法相同的参数


这些方法应该在C#driver中可用。

Hmm。。我不知道如何在没有未知类型的反射的情况下做到这一点。Thanx很多。这正是我想要的。非常好的答案,我发现唯一一个在编译时反序列化未知类的完整答案。
BsonClassMap.RegisterClassMap<MyDerivedClass>();
Type myDerivedClass; // your plugged-in class
var registerClassMapDefinition = typeof(BsonClassMap).GetMethod("RegisterClassMap", new Type[0]);
var registerClassMapInfo = registerClassMapDefinition.MakeGenericMethod(myDerivedClass);
registerClassMapInfo.Invoke(null, new object[0]);
public class MyBsonClassMap
{
    public static void RegisterClassMap(Type type)
    {
        Type bsonClassMapType = typeof(BsonClassMap<>).MakeGenericType(new Type[] { type });
        BsonClassMap bsonClassMap = (BsonClassMap)Activator.CreateInstance(bsonClassMapType);
        BsonClassMap.RegisterClassMap(bsonClassMap);
    }

    public static void RegisterClassMap(Type type, Action<BsonClassMap> classMapInitializer)
    {
        Type bsonClassMapType = typeof(BsonClassMap<>).MakeGenericType(new Type[] { type });
        BsonClassMap bsonClassMap = (BsonClassMap)Activator.CreateInstance(bsonClassMapType);
        classMapInitializer(bsonClassMap);
        BsonClassMap.RegisterClassMap(bsonClassMap);
    }
}
Type unknownType; // is the type that was unknown at compile time
MyBsonClassMap.RegisterClassMap(unknownType);
MyBsonClassMap.RegisterClassMap(unknownType, cm =>
     cm.AutoMap());