12

我有一个类似的对象:

[BsonKnownTypes(typeof(Bike), typeof(Car), typeof(Van))]
public class Vehicle
{
    public List<Wheel> wheels;
}

public class Bike: Vehicle
{

}

public class Car: Vehicle
{

}

public class Van: Vehicle
{

}

[BsonKnownTypes(typeof(WheelA), typeof(WheelB))]
public class Wheel
{

}

public class WheelA: Wheel
{
    private int Propa;
}

public class WheelB: Wheel
{
    private int Propb;
}

我有一个名为 vehicle 的集合,并将所有派生对象存储在这个集合中。Vehicle 具有“Wheel”类型的嵌入式对象集合。如果我的收藏有不同类型的轮子,则这些类型不会被反序列化。有没有办法可以将多态性用于嵌入式对象。

4

2 回答 2

18

尝试注册派生类型,例如:

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能够对其进行测试。
测试是绿色的。

于 2013-01-04T19:37:12.170 回答