我有四個簡單的類MongoDB的自定義集合串行
public class Zoo{
public ObjectId Id { get; set; }
public List<Animal> Animals { get; set; }
}
public class Animal{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
public class Tiger : Animal{
public double Height { get; set; }
}
public class Zebra : Animal{
public long StripesAmount { get; set; }
}
我創建了自定義序列化,讓我存儲在不同的收集動物對象(「動物」)。
class MyAnimalSerializer : SerializerBase<Animal>
{
public override void Serialize(MongoDB.Bson.Serialization.BsonSerializationContext context, MongoDB.Bson.Serialization.BsonSerializationArgs args, Animal value)
{
context.Writer.WriteStartDocument();
context.Writer.WriteName("_id");
context.Writer.WriteObjectId(ObjectId.GenerateNewId());
context.Writer.WriteName("_t");
context.Writer.WriteString(value.GetType().Name);
context.Writer.WriteName("Name");
context.Writer.WriteString(value.Name);
switch (value.AnimalType)
{
case AnimalType.Tiger:
context.Writer.WriteName("Height");
context.Writer.WriteDouble((value as Tiger).Height);
break;
case AnimalType.Zebra:
context.Writer.WriteName("StripesAmount");
context.Writer.WriteInt32((value as Zebra).StripesAmount);
break;
default:
break;
}
context.Writer.WriteEndDocument();
}
public override Animal Deserialize(MongoDB.Bson.Serialization.BsonDeserializationContext context, MongoDB.Bson.Serialization.BsonDeserializationArgs args)
{
context.Reader.ReadStartDocument();
ObjectId id = context.Reader.ReadObjectId();
string object_type = context.Reader.ReadString();
string animal_name = context.Reader.ReadString();
switch (object_type)
{
case "Tiger":
double tiger_height = context.Reader.ReadDouble();
context.Reader.ReadEndDocument();
return new Tiger()
{
Id = id,
Name = animal_name,
Height = tiger_height
};
default:
long zebra_stripes = context.Reader.ReadInt64();
context.Reader.ReadEndDocument();
return new Zebra()
{
Id = id,
Name = animal_name,
StripesAmount = zebra_stripes
};
}
return null;
}
}
效果很好,也讓我這樣的事情:
MongoDB.Bson.Serialization.BsonSerializer.RegisterSerializer(typeof(Animal), new MyAnimalSerializer());
IMongoCollection<Animal> collection = db.GetCollection<Animal>("animals");
var lst = await collection.Find<Animal>(new BsonDocument()).ToListAsync();
但我不能做同樣的,當動物被保存在動物園 ,不能從動物園收集反序列化動物園:
IMongoCollection<Zoo> collection = db.GetCollection<Zoo>("zoocollection");
var lst = await collection.Find<Zoo>(new BsonDocument()).ToListAsync(); //not working here
它是pos sible爲該字段創建自定義集合序列化程序?
public List<Animal> Animals { get; set; }
任何人都可以舉個例子嗎? 在此先感謝。
Ahaha!非常感謝你!我做了完全相同的事情,並且出於某種原因(我認爲有一點小錯誤)並不適合我!之後,它開始工作))同時,我爲這項任務寫了另一個解決方案。我會在下面發佈。 再次感謝。伊萬。 –