【问题标题】:Mongo c# driver customize serialization for generic typeMongo c#驱动为泛型自定义序列化
【发布时间】:2013-01-28 10:54:42
【问题描述】:

mongo c# 驱动程序有一些问题。我有这样的课:

class MongoEntity<T>
{
    public ObjectId Id {get; set;}
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public int Version { get; set; }
    public T Entity { get; set; }
}

在将我的实体序列化到数据库期间,我有这样的文档:

"_id" : "510654cf33d22e1774d5a2a9",
"CreatedAt" : {
    "DateTime" : ISODate("2013-01-28T10:37:02.932Z"),
    "Ticks" : NumberLong("634949662229321756")
 },
 "UpdatedAt" : {
    "DateTime" : ISODate("2013-01-28T10:37:02.932Z"),
    "Ticks" : NumberLong("634949662229321756")
 },
 "Version" : 1,
 "Entity" : {
    "EntityKey" : "tom@gmail.com",
    "Password" : "ICy5YqxZB1uWSwcVLSNLcA==",        
    "Email" : "tom@gmail.com",
    "Name" : "Tom Anderson"
 }

我真正想要的是让我的文档中实体对象的所有属性与 MongoEntity 对象的属性处于同一级别,如下所示:

"_id" : "510654cf33d22e1774d5a2a9",
"CreatedAt" : {
    "DateTime" : ISODate("2013-01-28T10:37:02.932Z"),
    "Ticks" : NumberLong("634949662229321756")
 },
 "UpdatedAt" : {
    "DateTime" : ISODate("2013-01-28T10:37:02.932Z"),
    "Ticks" : NumberLong("634949662229321756")
 },
 "Version" : 1,
 "EntityKey" : "tom@gmail.com",
 "Password" : "ICy5YqxZB1uWSwcVLSNLcA==",        
 "Email" : "tom@gmail.com",
 "Name" : "Tom Anderson"

没有实体嵌入对象。我怎样才能以最简单的方式实现这一点?

附:我真正在寻找的是驱动程序的一些配置或编写自定义序列化程序,也许是一些动态的解决方法,我不想改变当前的类结构Enteties MongoEntity

谢谢帮助。

【问题讨论】:

  • 您是否尝试过创建基类的子类而不是使用泛型类型?
  • 谢谢,我添加了“p.s.”部分解释了我正在寻找的解决方案。

标签: c# mongodb mongodb-.net-driver


【解决方案1】:

无法配置内置序列化程序来生成您想要的文档格式(实体字段提升了一级)。

您必须编写自定义序列化程序,但这会很困难,因为您必须为每个 编写一个新的序列化程序,或者您必须编写一个适用于任何 的复杂序列化程序。

WiredPrairie 的建议 (Person : MongoEntityBase) 是推荐的解决方案。

【讨论】:

    【解决方案2】:

    只需使用包含所有必需数据库字段的基本类型的子类。

    public class abstract MongoEntityBase
    {
        public ObjectId Id {get; set;}
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }
        public int Version { get; set; }
    }
    

    然后,使用它:

    public class Person : MongoEntityBase
    {
        public string Email { get; set; }
        public string Name { get; set; }
    }
    

    10gen 提供的 MongoDB C# 驱动程序在该模式下工作得很好。

    【讨论】:

    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多