Entity Framework: How to map a complex object to a single varchar column (i.e. save it in serialized form)?

StackOverflow https://stackoverflow.com/questions/23635716

I have an Entity where one of its properties is a complex object. I would like to represent this object in my DB as a serialized string (JSON to be specific).

How can I configure Entity Framework (I'm using v6.0) to map the above to a varchar, rather than the default EF behavior of auto-mapping it to tables and columns?

有帮助吗?

解决方案

Unfortunately this kind of property mapping is still not supported by Entity Framework. You probably have to fall back to tricks like this:

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

    public string MySerializedComplexType
    {
        get { return Serialize(MyComplexType); }
        set { MyComplexType = Deserialize(value); }
    }
    //...
}

(Instead of the [NotMapped] attribute you can use modelBuilder.Entity<MyEntity>().Ignore(e => e.MyComplexType) if you prefer Fluent API.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top