2014-09-30 110 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); 
     } 
    } 
}