【问题标题】:MongoRepository inheritance serialization errorMongoRepository 继承序列化错误
【发布时间】:2013-12-28 03:05:49
【问题描述】:

在尝试将继承与 MongoRepository for C# 结合时,我遇到了序列化错误。

真正奇怪的是它可以在很短的时间内工作,但在说重建或其他事情之后它就失败了。如果我删除该集合并创建一个新集合,它将一直有效,直到停止或重建。

我的代码如下:

public class Organization
{
      // other attributes removed for demonstration simplicity

      public List<Person> People { get;set; }
}

public abstract class Person
{
      public string Id {get;set;}
      public string Name {get;set;}
}

public class Employee : Person 
{
      public string Badge {get;set;}
}

public class Contractor : Person
{
     public string Company {get;set;}
}

当我尝试得到它时:

static MongoRepository<Organization> apps = new MongoRepository<Organization>();
return apps.Single(c => c.Id == id);

我收到的错误是:

MongoDB.Driver.dll 中出现“System.IO.FileFormatException”类型的异常,但未在用户代码中处理

附加信息:反序列化类 API.Models.Organization 的 People 属性时出错:无法创建抽象类的实例。

【问题讨论】:

    标签: c# mongodb serialization mongorepository


    【解决方案1】:

    添加装饰器属性:

    [BsonKnownTypes(typeof(Contractor), typeof(Employee))]
    

    类解决了这个问题。

    【讨论】:

    【解决方案2】:

    有一个类似的问题,其中Person 是一个继承自另一个抽象类的抽象类。我不喜欢将 Mongo 属性放在我的域模型中的想法,在稍微摆弄了一下之后,发现将 Person 类标记为根可以使其正确序列化和反序列化:

    BsonClassMap.RegisterClassMap<Person>(cm => {
        cm.SetIsRootClass(true);
    });
    

    请注意,发生反序列化异常是因为 MongoDB 驱动程序未设置鉴别器 _t 字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多