Search code examples
c#.netmongodb.net-coremongodb-.net-driver

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?


Solution

  • 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.