Houndolon Houndolon - 3 months ago 90
C# Question

MongoDB .NET: Mapping inherited generic property

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"));
});

Answer

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.

Comments