c# - 将对象反序列化为 MongoDB C# 驱动程序的接口(interface)

标签 c# mongodb mongodb-.net-driver

我正在开发一个使用 MongoDB(带有 C# 驱动程序)和 DDD 的项目。

我有一个类 (aggregate),它有一个类型是接口(interface)的属性。在另一个类中,我实现了这个接口(interface)。这个类有另一个属性,它的类型是一个接口(interface),并且是用另一个实现的类来设置的。

下面的代码解释得更好:

// Interfaces
public interface IUser {
    Guid Id { get; set;}
    IPartner Partner{ get; set; }
}

public interface IPartner {
    IPhone Mobile { get; set; }
}

public interface IPhone {
    string number { get; set; }
}

// Implemented Classes
public class User: IUser {
    [BsonId(IdGenerator = typeof(GuidGenerator))]
    public Guid Id { get; set; }

    [BsonIgnoreIfNull]
    public IPartner Partner { get; set; }
}

public struct Partner : IPartner {
    public IPhone Mobile { get; set; }
}

public struct Phone : IPhone {
    public string Number { get; set; }
}

好吧,当我调用 MongoCollection<User>.Insert()方法,它会抛出两个异常:

System.IO.FileFormatException: An error occurred while deserializing the Partner property of class .User: An error occurred while deserializing the Phone property of class .Partner: Value class .Mobile cannot be deserialized. ---> System.IO.FileFormatException: An error occurred while deserializing the Mobile property of class .Partner: Value class .Phone cannot be deserialized. ---> MongoDB.Bson.BsonSerializationException: Value class .Phone cannot be deserialized.

然后,我在互联网上搜索了如何将类型反序列化为接口(interface),我想我必须有办法做到这一点:使用强制转换映射属性,使用 BsonClassMap.RegisterClassMap或编写自定义 BSON 序列化程序。

我需要知道这两种方式中哪一种更好以及如何实现。

注意:我需要一个不修改接口(interface)的解决方案,因为他们的项目不能包含任何外部引用。

最佳答案

好吧,我在尝试得到这个答案时发现了很多问题。

首先,MongoDB C# 驱动程序确实存在一些问题在反序列化接口(interface)时,就像 Craig Wilson 在这个问题评论中所说的那样,正如 the issue page 中所述.

这个问题的安全实现,就像我之前说的,真的可能是一个自定义的 BS​​ON 序列化器或一个特定的类映射,使用 BsonClassMap.RegisterClassMap

所以,我已经实现了类映射,问题仍然存在。

展望这个问题,我发现这个异常与驱动程序的另一个问题有关:反序列化structs时的问题

我已将项目回滚到初始状态(没有类映射或自定义序列化程序)并将结构类型更改为类类型,它工作了

在简历中,此异常错误与结构反序列化有关,与接口(interface)反序列化无关。


无论如何,这是一个真正的问题,第二个问题需要被视为一个错误而不是改进,就像第一个问题一样。

您可以在这些链接中找到问题:

关于c# - 将对象反序列化为 MongoDB C# 驱动程序的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14561809/

相关文章:

javascript - 如何编码字符串以在 JavaScript 中以 HTML 格式显示?

ruby - BSON::ObjectId 与 Mongo::ObjectID

javascript - 我可以在 Mongo Shell Javascript 文件中读取 csv 文件吗?

c# - CS0133 "The expression being assigned to ' identifier' must be constant”- 这背后的原因是什么?

c# - 如何缩短 BasedOn 样式

c# - long/int 到 UINT64 转换并返回到 C# 上的 long - 我什么时候可以丢失数据?

c# - Mongo C# JSON 阅读器期待一个值但发现 'replSetGetStatus'

c# - 在 MongoDB 中查询其 id-s 包含在列表中的文档

c# - InvalidOperationException : Can't compile a NewExpression with a constructor declared on an abstract class

c# - 如何在 C# Windows 窗体中删除绘制的圆圈?