July 21, 2018

If this sounds like something that will save you time on your projects, please do me a favour and check it out

I've been working on a new project called StellarAdmin that helps ASP.NET Core developers like you rapidly create admin screens for your application's Admin and Support users.

I have an entity in my Entity Framework model which has a property of type Dictionary<string, string> which I would like to store as a JSON string in a nvarchar field in my database.

The definition of the entity is as follows:

public class PublishSource { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption . Identity ) ] public int Id { get ; set ; } [ Required ] public string Name { get ; set ; } [ Required ] public Dictionary < string , string > Properties { get ; set ; } = new Dictionary < string , string > ( ) ; }

Converting this to and from a JSON document which can be stored in the database turns out to be pretty easy with the Value Conversions which were added in EF Core 2.1.

In the OnModelCreating method of the database context I just call HasConversion , which does the serialization and deserialization of the dictionary:

protected override void OnModelCreating ( ModelBuilder modelBuilder ) { base . OnModelCreating ( modelBuilder ) ; modelBuilder . Entity < PublishSource > ( ) . Property ( b => b . Properties ) . HasConversion ( v => JsonConvert . SerializeObject ( v ) , v => JsonConvert . DeserializeObject < Dictionary < string , string > > ( v ) ) ; }