'Is there a way to use `ClassMap` to map one document property to multiple class properties?
Let's say I have a mongo document that looks like this:
{
"name": "John Doe"
}
Now let's say my model looks like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Is it possible to map one property from the document to two properties in the model?
I tried a ClassMap like this:
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());
}
But I got an error:
"The property 'LastName' of type 'Person' cannot use element name because it is already being used by property 'FirstName'."
Is there a way to allow this with ClassMap?
Solution 1:[1]
It doesn't look like it's possible, but if you can add properties to your model, then Alexandra Petrova's solution might work for you.
Solution 2:[2]
You can mark the two properties as read-only and compute their value from the name property.
public class Person
{
public string Name { get; set; }
public string FirstName => Name.Split(" ").First();
public string LastName => Name.Split(" ").Last();
}
As stated in the documentation (Opt-in section)
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.
By taking this approach, you don't need to write custom serializers, and those two additional properties won't be mapped in the document by default, so no need to add additional class map rules.
Also, in case you don't want to allow changes of the Name property, you can create a constructor for the model and mark the set as 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();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rokit |
| Solution 2 | Alexandra Petrova |
