Support for Inheritance in properties in C# mongodb driver

I have two separate entities, one is BaseSchema and another is BaseValidator.

Parent class

[BsonDiscriminator("baseSchema")]
    [BsonKnownTypes(typeof(CharFieldSchema))]
    public class BaseSchema
    {
        public string Id { set; get; }
        public virtual string Type { get; }
        public string Label { set; get; }
        public bool Visibility { set; get; }
        public string Hint { set; get; }
        public **BaseValidator Validator** { set; get; }
    }

child class

[BsonKnownTypes(typeof(MultiLineSchema),typeof(SingleLineSchema),typeof(NumberSchema))]
    public class CharFieldSchema : BaseSchema
    {
        public override string Type { get; } = "charField";
        public string DefaultValue { set; get; }
    
        public string Prefix { set; get; }
        public string Suffix { set; get; }
        public new **CharFieldValidator Validator** { set; get; }
    }

This is another validator entity…

BaseValidator

 [BsonDiscriminator("baseValidator")]
    [BsonKnownTypes(typeof(CharFieldValidator))]
    public class BaseValidator
    {
        // public virtual string Type { get; }
        public bool Require { get; }
    }

CharFieldValidator

    [BsonKnownTypes(typeof(MultiLineValidator), typeof(NumberValidator), typeof(SingleLineValidator))]
    public class CharFieldValidator : BaseValidator
    {
        // public override string Type { get; } = "charFieldV";
        public int MinLength { set; get; }
        public int MaxLength { set; get; }
    }

But the problem is getting error for using Validator property name in BaseSchema and CharFieldSchema, since the name of the field is same called Validator but only datatype is different (inherited from BaseValidator).

Getting error : MongoDB.Bson.BsonSerializationException: The property 'Validator' of type 'Dto.FormSchema.CharFieldSchema' cannot use element name 'Validator' because it is already being used by property 'Validator' of type 'Dto.FormSchema.BaseSchema'.

Is it any way to add support for this? (without renaming the property name by using [BsonElement("someName")]).

2 Likes