C# MongoDb serialization of Dictionary<string, object>

删除回忆录丶 提交于 2019-12-05 22:19:14

So works MongoDriver, because it needs information of the type to deserilize it back. What you could do, is to write and register your own CustomMapper for User class:

public class CustomUserMapper : ICustomBsonTypeMapper
{
    public bool TryMapToBsonValue(object value, out BsonValue bsonValue)
    {
        bsonValue = ((User)value).ToBsonDocument();
        return true;
    }
}

Somewhere on starting program:

BsonTypeMapper.RegisterCustomTypeMapper(typeof(User), new CustomUserMapper());

That will work, and i have managed to serialize your data exact as you want.

But: As you want to deserialize it back, you wil get your User class as Dictionary, because driver will have no information about hiow to deserialize it:

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