What is a value converter in EF Core?
Quick Answer
A value converter transforms a property between its CLR representation and how it's stored in the column. Use HasConversion to store an enum as a string, a value object as its primitive, a list as JSON, or to encrypt a column — the entity keeps the nice type, the database gets the storable form.
A value converter sits between the property type in your code and the column type in the database. The everyday use is HasConversion<string>() on an enum so the database stores “Active” instead of an int that breaks if someone reorders the enum. It's also how you persist a value object like an EmailAddress as a plain string, or store a small list as JSON, or transparently encrypt a column. The thing to watch is that filtering on a converted column doesn't always translate to SQL cleanly.
builder.Property(o => o.Status).HasConversion<string>();— enum stored as text (readable in the DB, safe against reordering).HasConversion(v => v.Value, v => new EmailAddress(v))— a value object stored as a string.- Built-in converters exist for common cases; you can also write an
EncryptingConverter. - Caveat: a converted column can't always be translated in a
WHEREthe way a native column can — check the generated SQL, and prefer converting to a type the provider understands.