Getting an error when trying to retrieve objects from mongodb:
InvalidOperationException: Can't compile a NewExpression with a constructor declared on an abstract class
My class is:
public class App
{
public List<Feature> Features { get; set; }
}
public abstract class Feature
{
public string Name { get; set; }
}
public class ConcreteFeature : Feature
{
public string ConcreteProp { get; set; }
}
Not sure why it is having issues with abstractions. I see, mongodb recorded _t: "ConcreteFeature"
type name, it has everything to deserialize it. I have no constructor in abstract class.
Ideas?
I needed to list "KnownTypes" for BsonClassMap to make it work:
BsonClassMap.RegisterClassMap<Feature>(cm => {
cm.AutoMap();
cm.SetIsRootClass(true);
var featureType = typeof(Feature);
featureType.Assembly.GetTypes()
.Where(type => featureType.IsAssignableFrom(type)).ToList()
.ForEach(type => cm.AddKnownType(type));
});
This way you won't need to touch the code even if you add new types as long as they are in 1 assembly. More info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With