C# 10gen and mongo: deserialization for members as interfaces

你说的曾经没有我的故事 提交于 2019-12-12 04:47:23

问题


All

Consider this example:

    private class CollectionHolder
    {
        public ObjectId Id { get; set; }
        public MyCollection Collection { get; set; }
    }

    private class MyCollection : List<int>
    {
        public MyCollection(List<int> a)
        {
            this.AddRange(a);
        }
    }

    private static void CollectionTest()
    {
        var collection = database.GetCollection<MyCollection>("collectionTest");
        collection.RemoveAll();
        collection.Save(new CollectionHolder { Collection = new MyCollection(new List<int> { 1, 2, 3, 4, 5 }) });
        var x = collection.AsQueryable().First(); //exception!
        x.ForEach(Console.WriteLine);
    }

The marked line throws exception

An error occurred while deserializing the Collection property of class MongoDriverTest.Program+CollectionHolder: An error occurred while deserializing the Capacity property of class MongoDriverTest.Program+MyCollection: Object reference not set to an instance of an object.

I am not sure, is this a bug in 10gen mongo driver, or is this impossible to implement? How do You think, should this be posted as a bug?

Moreover -- what is the best way to avoid such kind of errors?


回答1:


Currently, custom collections are not supported. There is already implemented in master and will exist in release 1.5 for this. Until then, you can't use custom collections to get the behavior you are requesting.




回答2:


The problem with custom collections in 1.4.2 and earlier is that since there is no serializer registered for your custom collection the C# driver attempts to serialize it using the BsonClassMapSerializer. But the BsonClassMapSerializer requires the class being serialized to expose all the data to be serialized as public get/set properties (which your base class List<T> does not).

The only thing that changes in 1.5 is how the driver chooses which serializer to use when a POCO implements IEnumerable or IDictionary.

You can use custom collections already in 1.4.2 and earlier by explicitly registering a serializer for your custom collection like this:

BsonSerializer.RegisterSerializer(typeof(MyCollection), new EnumerableSerializer<int>());


来源:https://stackoverflow.com/questions/10831706/c-sharp-10gen-and-mongo-deserialization-for-members-as-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!