I have the following class which represents an entity in a MongoDB database:
public class Profile
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = null!;
[BsonElement("FirstName")]
[JsonPropertyName("FirstName")]
public string? FirstName { get; set; }
[BsonElement("LastName")]
[JsonPropertyName("LastName")]
public string? LastName { get; set; }
}
I have deprecated the FirstName
and LastName
fields using the [Obsolete]
annotation and added a FullName
field:
public class Profile
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = null!;
// Deprecate
[Obsolete]
[BsonElement("FirstName")]
[JsonPropertyName("FirstName")]
public string? FirstName { get; set; }
// Deprecate
[Obsolete]
[BsonElement("LastName")]
[JsonPropertyName("LastName")]
public string? LastName { get; set; }
// New field
[BsonElement("FullName")]
[JsonPropertyName("FullName")]
public string? FullName { get; set; }
}
The problem is that writing new objects to the MongoDB database still writes the old fields as null. I want to prevent this from happening without removing the fields from the class, because it needs to be backward compatible with the old objects in the database. How can I solve this?