C# · 12月 26, 2021

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;}

我有一个名为车辆的集合,并将所有派生对象存储在此集合中.车辆已经为“轮”类型嵌入物体集合.如果我的收藏有不同类型的轮子,那些类型不会被反序列化.有没有办法可以使用嵌入式对象的多态.

解决方法 尝试注册派生类型,如: 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& Propb,被公开.我还向Vehicle添加了一个Id字段,以便能够测试它.测试是绿色的