尝试注册派生类型,例如:
BsonClassMap.RegisterClassMap<WheelA>();
BsonClassMap.RegisterClassMap<WheelB>();
或喜欢:
[BsonDiscriminator(Required = true)]
[BsonKnownTypes(typeof(WheelA), typeof(WheelB))]
public class Wheel
更新:在创建测试项目时,我意识到:您需要将属性设为 public。
如果它们不可访问,MongoDB 无法设置它们。
这是测试代码:
[TestClass]
public class IntegrationTests
{
[TestMethod]
public void Polymorphic_objects_should_deserialize()
{
var database = MongoDatabase.Create("connection_string");
var collection = database.GetCollection("vehicles");
var car = new Car
{
wheels = new List<Wheel>
{
new WheelA {propA = 123},
new WheelB {propB = 456}
}
};
collection.Insert(car);
var fetched = collection.AsQueryable<Car>()
.SingleOrDefault(x => x.Id == car.Id);
Assert.IsNotNull(fetched.wheels);
Assert.AreEqual(2, fetched.wheels.Count);
Assert.IsInstanceOfType(fetched.wheels[0], typeof(WheelA));
Assert.IsInstanceOfType(fetched.wheels[1], typeof(WheelB));
Assert.AreEqual(123, (fetched.wheels[0] as WheelA).propA);
Assert.AreEqual(456, (fetched.wheels[1] as WheelB).propB);
}
}
这些实体与您的列表相同,除了Propa
& Propb
,它是公开的。
我还添加了一个Id
字段以便Vehicle
能够对其进行测试。
测试是绿色的。