Entity Framework Core Interview Question #152

How do you create a custom value converter?

Advanced Mapping, Interceptors, Value Conversions & Architecture Senior Advanced

Quick Interview Answer

A custom converter defines expressions for converting a model value to a provider value and converting the provider value back to the model type. It is useful for strongly typed value objects and specialized storage formats. The conversion should be deterministic and compatible with query translation requirements.

Detailed Explanation

A custom converter defines expressions for converting a model value to a provider value and converting the provider value back to the model type. It is useful for strongly typed value objects and specialized storage formats. The conversion should be deterministic and compatible with query translation requirements.

Code Example

var converter = new ValueConverter<EmailAddress, string>(
    v => v.Value,
    v => new EmailAddress(v));

modelBuilder.Entity<Customer>()
    .Property(c => c.Email)
    .HasConversion(converter);