Entity Framework Core Advanced

Value conversions

Value converters change how a property is stored without changing your C# type. This lesson shows the common cases: enums as text, strongly typed ids, encrypted or trimmed values and DateTime kinds, plus how to apply a converter to every property of a type.

A converter at work
  1. StartC# valueOrderStatus.Paid
  2. Step 2Converter to provider"Paid"
  3. Step 3Database columnStatus nvarchar(20) = 'Paid'
  4. EndConverter from providerBack to OrderStatus.Paid when read

What a converter does

A converter has two functions: one from your C# value to the database value, and one back. EF Core runs them when saving and reading, and translates query constants too, so Where(o => o.Status == OrderStatus.Paid) still works in SQL.

Enums as text

By default enums are stored as numbers. Storing them as text makes the data readable and safe from reordering the enum.

C#
public enum OrderStatus { New, Paid, Shipped, Cancelled }

modelBuilder.Entity<Order>()
    .Property(o => o.Status)
    .HasConversion<string>()
    .HasMaxLength(20);

// Or for every enum property of this type in the model
protected override void ConfigureConventions(ModelConfigurationBuilder b)
{
    b.Properties<OrderStatus>().HaveConversion<string>().HaveMaxLength(20);
}

Strongly typed ids

A readonly record struct ProductId stops you from passing an OrderId where a ProductId is expected. A converter stores it as a plain int.

C#
public readonly record struct ProductId(int Value);

public class Product
{
    public ProductId Id { get; set; }
    public string Name { get; set; } = "";
}

modelBuilder.Entity<Product>()
    .Property(p => p.Id)
    .HasConversion(id => id.Value, value => new ProductId(value))
    .ValueGeneratedOnAdd();

Good to know

  • Built-in converters include BoolToStringConverter, DateTimeToTicksConverter and many others; HasConversion<T>() picks one for you.
  • Queries such as Contains or string functions on a converted value may not translate; keep conversions simple.
  • To mark DateTime values read from the database as UTC, use a converter that calls DateTime.SpecifyKind(v, DateTimeKind.Utc).
  • Converters do not change the column for existing data; add a migration and convert data when switching.

Interview question

Why might you store an enum as a string instead of an integer?

Text values are readable in the database, in reports and in other apps, and they do not break if someone reorders or inserts enum members, which would silently change the meaning of stored numbers. The costs are a little more storage and the need for a max length. In EF Core, HasConversion<string>() does it.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.