2

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?

0

1 Answer 1

2

You can add [BsonIgnoreIfNull] attribute to both FirstName and LastName so that when the property's value is null, the property will not be serialized and included when writing in the database.

public class Profile
{
    // Deprecate
    [Obsolete]
    [BsonElement("FirstName")]
    [BsonIgnoreIfNull]
    [JsonPropertyName("FirstName")]
    public string? FirstName { get; set; }

    // Deprecate
    [Obsolete]
    [BsonElement("LastName")]
    [BsonIgnoreIfNull]
    [JsonPropertyName("LastName")]
    public string? LastName { get; set; }

    ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.