有没有一种方法可以使用 `ClassMap` 将一个文档 属性 映射到多个 class 属性?

Is there a way to use `ClassMap` to map one document property to multiple class properties?

假设我有一个 mongo 文档,如下所示:

{
    "name": "John Doe"
}

现在假设我的模型如下所示:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

是否可以将文档中的一个 属性 映射到模型中的两个属性?

我试过 ClassMap 这样的:

BsonClassMap.RegisterClassMap<Person>(cm =>
{
    cm.AutoMap();
    cm.MapMember(c => c.FirstName).SetElementName("name").SetSerializer(new FirstNameSerializer());
    cm.MapMember(c => c.LastName).SetElementName("name").SetSerializer(new LastNameSerializer());
}

但是我得到一个错误:

"The property 'LastName' of type 'Person' cannot use element name because it is already being used by property 'FirstName'."

有没有办法允许 ClassMap

您可以将这两个属性标记为 read-only 并根据 name 属性.

计算它们的值
public class Person
{
     public string Name { get; set; }

     public string FirstName => Name.Split(" ").First();

     public string LastName => Name.Split(" ").Last();
}

documentation(Opt-in 部分)所述

A majority of classes will have their members mapped automatically. There are some circumstances where this does not happen. For instance, if your property is read-only, it will not get included in the automapping of a class by default.

通过采用这种方法,您无需编写自定义序列化程序,并且默认情况下不会将这两个附加属性映射到文档中,因此无需添加额外的 class 映射规则。

此外,如果您不想允许更改 Name 属性,您可以为模型创建构造函数并将集合标记为 private

public class User
{
    public User(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    public string FirstName => Name.Split(" ").First();

    public string LastName => Name.Split(" ").Last();
}

看起来不太可能,但如果您可以向模型添加属性,那么 可能适合您。