Published in


Entity Framework Core: Expanding a column into multiple entity properties

When working on composing an Entity Framework Core 2.1 course, I stumbled upon the ValueConverter feature.

This allows you to hook into the middle of the conversion from a specific column into a custom property on your entity class and vice-versa.

The first use-case I’d come up with is JSON serialized data in a SqlServer column. We currently have something like this set up in a project of ours and it looks promising. In fact, it’s already done.

Let’s look into writing an expanded column property.

The model is based on the DimCustomer table of the AdventureWorksDW database from the samples database repo.

In our application, we’d like to show a birthday-countdown for each of our customers, but instead of deserializing the date, we’d want to store this in a custom expanded property, BirthDay.

But there’s no way EF can implicitly convert from a database-type into custom CLR type. So we’ll need to write the conversion ourselves.

For the BirthDay property of the Customer entity type, we’re specifying which column we want to target (BirthDate) and specify a conversion via the HasConversion extension method, which takes two parameters:

  • The conversion from the property to the column
  • The conversion from the column to the property

Please keep in mind that the returned type from the first parameter needs to be a supported EF type, otherwise the building of the model will fail at runtime

With the conversion in place, we can now leverage the DaysToNextBirthDay method and let our customers count down to their next birthday!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store