Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException: Can't compile a NewExpression with a constructor declared on an abstract class

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?

like image 955
Andrei Avatar asked Jul 13 '19 03:07

Andrei


1 Answers

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.

like image 88
Andrei Avatar answered Sep 18 '22 20:09

Andrei