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

Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top