Mongo DB类重构

时间:2015-11-10 15:53:46

标签: c# mongodb

在以下场景中覆盖Mongo Serializer的最佳方法是什么:

我有以下课程

public Class Quest
{
   public ObjectId _id {get; set;}
   public string Name {get; set;}
   public List<string> GalleryImagePaths {get; set;}
}

在重构练习之后,GalleryImagePaths属性被重构为

public List<HttpFile> GalleryImagePaths {get; set;}

public Class HttpFile 
{
  string FilePath {get; set;}
  string UriPath {get; set;}
}

现在默认的序列化程序无法反序列化为

List<string> GalleryImagePaths

新数据文档将存储在新架构中。

这里的最佳做法是什么?

1 个答案:

答案 0 :(得分:0)

BsonSerializer类是静态的,不可继承的,所以我认为自定义序列化程序在这种情况下会帮助序列化/反序列化。
例如:

using System.Reflection;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;

// Custom Serializer
public static class MyBsonSerializer
{
    public static Quest DeserializeQuest(BsonDocument bson)
    {
        Quest quest = new Quest();
        var properties = typeof(Quest).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();

        foreach (var element in bson.Elements)
        {
            switch (element.Name)
            {
                case "GalleryImagePaths":
                    List<HttpFile> paths = new List<HttpFile>();
                    foreach (var path in element.Value.AsBsonArray)
                    {
                        var httpFile = new HttpFile();
                        // Set FilePath and UriPath
                        paths.Add(httpFile);
                    }
                    quest.GalleryImagePaths = paths;
                    break;
                case "_id":
                    properties.First(p => p.Name == element.Name).SetValue(quest, new ObjectId(element.Value.ToString()));
                    break;
                case "Name":
                    properties.First(p => p.Name == element.Name).SetValue(quest, element.Value.ToString());
                    break;
            }
        }
        return quest;
    }

    public static BsonDocument SerializeQuest(Quest quest)
    {
        BsonDocument bson = new BsonDocument();
        bson.Add(new BsonElement("Name", quest.Name));
        var paths = quest.GalleryImagePaths.Select(h => h.UriPath); 
        // OR quest.GalleryImagePaths.Select(h => h.FilePath)
        bson.Add(new BsonElement("GalleryImagePaths", new BsonArray(paths)));

        return bson;
    }
}

反序列化:

var collection = db.GetCollection<BsonDocument>("Quest");
var filter = Builders<BsonDocument>.Filter.Eq("Name", "sample");
Quest quest = MyBsonSerializer.DeserializeQuest(collection.Find(filter).FirstOrDefault());

序列化(和插入):

collection.InsertOne(MyBsonSerializer.SerializeQuest(quest));