MongoDB Embedded多态对象

时间:2012-12-19 16:07:57

标签: c# mongodb

我有一个与此类似的对象:

[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的集合,并将所有派生对象存储在此集合中。车辆具有类型'Wheel'的嵌入式对象集合。如果我的集合有不同类型的轮子,那么这些类型不会被反序列化。有没有办法可以将多态性用于嵌入对象。

2 个答案:

答案 0 :(得分:14)

尝试注册派生类型,如:

BsonClassMap.RegisterClassMap<WheelA>();
BsonClassMap.RegisterClassMap<WheelB>();

或者喜欢:

[BsonDiscriminator(Required = true)]
[BsonKnownTypes(typeof(WheelA), typeof(WheelB))]
public class Wheel

更新:在创建测试项目时,我意识到:您需要公开属性
如果它们不可访问,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&amp; Propb,已公开 我还在Id添加了Vehicle字段,以便对其进行测试 测试是绿色的。

答案 1 :(得分:1)