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
- Centralized logic: Define once, apply everywhere.
- Cleaner entities: No need for extra backing fields or manual conversions.
- Consistency: Guarantees that data is always stored and retrieved in the expected format.
- Security, performance & maintenance: Perfect for scenarios like hashing, sanitization, or normalization and my favourite enum to string.
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.