1

I have a generic class Parameter with a generic property Value:

abstract class Parameter<T> {
    public T Value { get; set; }
}

StringParameter class inherits the Parameter class:

class StringParameter : Parameter<string> {
    //...
}

Is it possible to properly map the StringParameter class so that it contains the generic Value property?

When trying to map the StringParameter class with the code below (and various other approaches) the best I could do is get an exception with the message: "The memberInfo argument must be for class StringParameter, but was for class Parameter`1."

BsonClassMap.RegisterClassMap<StringParameter>(cm => {
    cm.AutoMap();
    cm.MapMember(typeof(StringParameter).GetRuntimeProperty("Value"));
});

1 Answer 1

2

Mapping the Parameter class with the specified type parameter for every subclass that inherits it and then automapping each subclass seems to have done the trick.

BsonClassMap.RegisterClassMap<Parameter<string>>(cm => {
    cm.AutoMap();
    cm.MapProperty("Value");
});
BsonClassMap.RegisterClassMap<Parameter<DateTime>>(cm => {
    cm.AutoMap();
    cm.MapProperty("Value");
});
BsonClassMap.RegisterClassMap<Parameter<int>>(cm => {
    cm.AutoMap();
    cm.MapProperty("Value");
});
BsonClassMap.RegisterClassMap<Parameter<decimal>>(cm => {
    cm.AutoMap();
    cm.MapProperty("Value");
});

BsonClassMap.RegisterClassMap<StringParameter>();
BsonClassMap.RegisterClassMap<DateParameter>();
BsonClassMap.RegisterClassMap<IntegerParameter>();
BsonClassMap.RegisterClassMap<DecimalParameter>();

Note that this maps all the Parameter classes into a single collection with appropriate discriminators.

Sign up to request clarification or add additional context in comments.

Comments

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.