Let’s assume that we have such read model:

And we want store Category and FieldValues in the table, as JSON string.  How to handle JSON serialization and deserialization in Dapper?


TypeHandlers are an option in Dapper to serialize / deserialize objects during saving and querying the database. First, we define an implementation of ITypeHandler interface:

SetValue method returns serialized object to JSON string, handling also the null value. Parse method returns deserialized object from the database column.

Then we register our type handlers during app startup:

In that way, we achieve seamless objects serialization and deserialization without changing our code.

Private fields

I like to keep my class setters private to force usage of strictly defined changing methods.

But on another hand, we want to gather full object from the database. To achieve it we inherit from DefaultContractResolver and allow setting also private fields:

Then we register resolver during app startup: