Skip to content

Entity Framework Value Converters

Published: at 07:27 AM

Value Converters Are Awesome!

Entity Framework Core (v2.1) introduced Value Converters as a way to transparently transform data between your domain model and the database. I find it brilliant; instead of scattering transformation logic across your application, you can centralize it in the model configuration. To me it’s a jump from what typically needs to be in a Model View to the EF builder - where it makes so much sense!

Why Value Converters Are Awesome

Example 1: Enum to String Conversion

Enums are great in code, but sometimes you want to store them as strings unless you’re using them with Flags. Because, someone can add new values to an enum (in the middle of other existing values) and that won’t update the values already saved to the database.

builder.Property(e => e.Status)
    .HasConversion(
        v => v.ToString(),
        v => (Status)Enum.Parse(typeof(Status), v)
    );

Example 2: HTML Sanitization

builder.Property(e => e.HtmlContent)
    .HasConversion(
        v => HtmlSanitizer.Clean(v),
        v => v                       // read as-is
    );

This guarantees that every time HTML content is persisted, it’s cleaned of unsafe tags and attributes.


Next Post
Prepare ESP32 with CP2102 Driver and nanoFramework