Saturday, August 10, 2019

Json Serialzation in Entity Framework (EF Core 2.1)

I've had a number of instances where I want to serialize JSON into a single field in the database. In the past I resorted to a [NotMapped] field which held the complex object and a [JsonIgnore]d field which was serialized in EF to a Text SQL field.

I recently discovered that EF Core 2.1 includes easy value conversions! In the example below, I have a Stay entity which has a serialized Drive object. Drive is declared on SQL Server as a Text column.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);


   modelBuilder.Entity<Stay>()
   .Property(s => s.Drive)
   .HasConversion(
      d => JsonConvert.SerializeObject(d),
      d => JsonConvert.DeserializeObject<Drive>(d)
   );
}


Viola! No need for the extra fields on the model class.