EntityFramework - mapping a complex property to a json (string) column

I have the following entity:

public class SampleClass { public int Id { get; set; } public object Args {get; set; } } 

Because Args can be of different types and does not need a request, I want to save it in the database as a json string.

I know the following way to solve my problem:

 public class SampleClass { public int Id { get; set; } public object Args { get { return Json.Deserialize(ArgsJson); } set { ArgsJson = Json.Serialize(value); } } public string ArgsJson {get; set; } } 

But this is pretty ugly, because it provides information not related to the model, and contains logic that is not related to the model again.

What I would like to do is something like this:

 public class SampleClassMapper : EntityTypeConfiguration<SampleClass> { public SampleClassMapper() { this.Property(e => e.Args).MapAs<string>(arg => Json.Serialize(arg), str => Json.Deserialize(str)); } } 

Is there a cool way to do this?

(I am using .Net 4.0 with EntityFramework 5 and Sql Server 2008, if that helps)

+4
source share
1 answer

What you do is the only one available at the moment in EF. EF Code First does not currently have an easy way to change the serialization of an object, but this can be done by modifying the EDMX file at run time.

+1
source

All Articles