实体框架:如何将复杂对象映射到单个varchar列(即以序列化形式保存)?

uri*_*rig 2 mapping serialization json entity-framework

我有一个实体,其中一个属性是一个复杂的对象.我想在我的数据库中将此对象表示为序列化字符串(特定于JSON).

如何配置实体框架(我使用v6.0)将上面的内容映射到varchar,而不是将其自动映射到表和列的默认EF行为?

Sla*_*uma 6

不幸的是,实体框架仍然不支持这种属性映射.你可能不得不回到这样的技巧:

public class MyEntity
{
    //...
    [NotMapped]
    public MyComplexType MyComplexType { get; set; }

    public string MySerializedComplexType
    {
        get { return Serialize(MyComplexType); }
        set { MyComplexType = Deserialize(value); }
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

(如果您更喜欢Fluent API,则[NotMapped]可以使用该属性modelBuilder.Entity<MyEntity>().Ignore(e => e.MyComplexType).)