2014-09-30 183 views
1

核心價值表我想在我沿着使用稍微修改sqlProvider的的的使用ServiceStack OrmLite創建動態類型

public class KeyValue { 
    public string Id { get; set; } 
    public dynamic Value {get; set; } 
} 

線我沒有問題得到CreateTable<KeyValue>()產生varchar(1024) Id數據庫中創建一個關鍵值表,varchar(max) Value

我沒有問題對象保存到它。問題是當我加載對象

var content = dbConn.GetById<KeyValue>("about"); 

content.Value在這一點上是一個字符串。

望着數據庫中記錄值的文本不會出現存儲任何類型的信息。

難道真有什麼我可以做的比手動調用​​,並呼籲反序列化使用合適的類型信息的更好其他?

我並不需要絕對的動態,我的實際使用情況是多態性與基類的,而不是動態的。所以,我真的不關心什麼類型的價值是,它是否是基類,動態對象等。不管比使用類

public class KeyValue { 
    public string Id { get; set; } 
    public MySpecificChildType Value {get; set; } 
} 

我一直沒能不是字符串得到其他任何東西等價值。我可以告訴OrmLite序列化類型信息以便能夠正確地反序列化我的對象,還是隻需手動執行?

編輯:一些進一步的信息。 OrmLite正在使用由ServiceStack.Text.TypeSerializer定義的Jsv序列化程序,並且不能在BSD版本中插入。如果我添加一個類型屬性,以我的動態值的鍵值類我可以做

var value = content.Value as string; 
MySpecificChildType strongType = 
       TypeSerializer.DeserializeFromString(content, content.Type); 

我真的想要一個更好的方式來做到這一點,我真的不喜歡1種類型的對象進入該數據庫以不同的類型(字符串)返回。

回答

2

我沒有太多的工作與JsvSerializer但與JsonSerializer你可以做到這一點(在幾個不同的方式),並作爲ServiceStack 4.0.11,你可以選擇使用JsonSerializer而是看https://github.com/ServiceStack/ServiceStack/blob/master/release-notes.md#v4011-release-notes

public abstract class BaseClass { 
    //Used for second example of custom type lookup 
    public abstract string Type { get; set; } 
} 

public class ChildA : BaseClass { 
    //Used for second example of custom type lookup 
    public override string Type { get; set; } 

    public string PropA { get; set; } 
} 

然後在你的初始化/自舉類,你可以配置串行發出需要進行適當的反序列化類型的信息:如果你想使用其他的東西,

public class Bootstrapper { 
    public void Init() { 
     ServiceStack.Text.JsConfig.ExcludeTypeInfo = false; 
     ServiceStack.Text.JsConfig.IncludeTypeInfo = true; 
    } 
} 

默認的「__type」屬性的ServiceStack用途(比如你想擁有一個友好的名稱,用於識別的類型而不是命名空間/組件),您還可以配置自己的自定義類型查找這樣

public class Bootstrapper { 
    public void Init() { 
     ServiceStack.Text.JsConfig.ExcludeTypeInfo = false; 
     ServiceStack.Text.JsConfig.IncludeTypeInfo = true; 

     ServiceStack.Text.JsConfig.TypeAttr = "type"; 
     ServiceStack.Text.JsConfig.TypeFinder = type => 
     { 
      if ("CustomTypeName".Equals(type, StringComparison.OrdinalIgnoreCase)) 
      { 
       return typeof(ChildA); 
      } 

      return typeof(BaseClass); 
     } 
    } 
}