Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.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# 基于接口的.Net MongoDB反序列化prop_C#_Mongodb_Interface_Deserialization_Mongodb .net Driver - Fatal编程技术网

C# 基于接口的.Net MongoDB反序列化prop

C# 基于接口的.Net MongoDB反序列化prop,c#,mongodb,interface,deserialization,mongodb-.net-driver,C#,Mongodb,Interface,Deserialization,Mongodb .net Driver,我有几个类标记了一个接口。例: public class Example1 : IExample {} public class Example2 : IExample {} public class Master { public string Company { get; set; } public IExample Examples { get; set; } } 在我的主类上,我有一个示例道具,但声明为接口。例: public class Example1 : IExam

我有几个类标记了一个接口。例:

public class Example1 : IExample {}

public class Example2 : IExample {}
public class Master
{
  public string Company { get; set; }

  public IExample Examples { get; set; }
}
在我的主类上,我有一个示例道具,但声明为接口。例:

public class Example1 : IExample {}

public class Example2 : IExample {}
public class Master
{
  public string Company { get; set; }

  public IExample Examples { get; set; }
}
为了更好地编写Mongo,Mongo添加了一个属性,该属性具有由接口签名的类的名称,例如Example1或Example2

但反序列化根本不起作用。抛出一个错误:

Exception thrown: 'System.FormatException' in MongoDB.Bson.dll: 'An error occurred while deserializing the Source property of class Audit.Processed: Unknown discriminator value 'Example1'.'
我必须注册一些东西或者添加一些东西的属性到Mongo理解这个类吗?为什么插入工作

我还发现了其他类似于这篇()的帖子,但它们都讨论基类,而不是作为属性的接口

正如checked post所说的那样工作,但我必须创建一个静态类,否则会抛出一个异常,表明已注册allready。以下是工作代码:

public class ClassMapRegisterer
{
    static ClassMapRegisterer()
    {
        BsonClassMap.RegisterClassMap<Example1>();
    }

    public static void RegisterClassMaps()
    {            
    }
}
干杯

根据:

如果您看到一条关于“未知鉴别器”的错误消息,那是因为反序列化程序无法找出该鉴别器的类。如果要以编程方式映射类,只需确保在开始反序列化之前已映射层次结构中的所有类

您不能使用
BsonKnowTypes
属性,因为当您有一个接口时,它仅限于classes和structs,但您可以使用
RegisterClassMap

BsonClassMap.RegisterClassMap<Example1>();
BsonClassMap.RegisterClassMap<Example2>();
BsonClassMap.RegisterClassMap();
BsonClassMap.RegisterClassMap();

您能告诉我您正在使用的反序列化程序吗?这有助于澄清错误的原因。成功!但是我必须创建一个静态类并将RegisterClassMap放在上面。另一种方法是抛出一个异常,表示类映射已注册就绪。谢谢