2015-11-10 139 views
1

什麼是覆蓋蒙戈串行下列情形的最佳方式:蒙戈DB類重構

我有以下類

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 

而新的數據文檔將被存儲在新的模式中。

這裏最好的做法是什麼?

回答

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