MongoDb C# Exception Happened When insert a interface property

Hi, I have a project worked with mongoDb Driver 2.2.0

And there’s a object defined as:

public class ClassToSave
{
    [BsonId] public int Id { get; set; } = 0;
    public IInterface[] Data { get; set; } = new IInterface[] { new ArrayItem() };
}


public class ArrayItem : IInterface
{
    [BsonId]
    public string Name { get; set; } = "Test";
}
public interface IInterface
{
    string Name { get; set; }
}

And the exception happened when insert data to db.

BsonClassMap.RegisterClassMap<ArrayItem>(cm =>
{
    var fullName = typeof(ArrayItem).FullName;
    cm.SetDiscriminator(fullName);
    cm.AutoMap();
    cm.SetIgnoreExtraElements(true);
});

var client = new MongoClient();
var db = client.GetDatabase("MyTest");
var collection = db.GetCollection<ClassToSave>("collection");
collection.InsertOne(new ClassToSave());

Detail of the Exception:
image

How can I solve this?

Hi, @wang_howard,

Welcome to the MongoDB Community Forums. I understand that you’re running into an exception when attempting to serialize a discriminated interface. Because the base class of your ArrayItem class is object, the type is serialized using the ObjectSerializer.

Due to a vulnerability in .NET involving type discriminators, you must declare types as safe to be used with the ObjectSerializer. You can find information about how to do this in our FAQ:

What Object Types Can Be Serialized?

Sincerely,
James