Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 41 ยท DbContext and Models

Value Converters and Owned Types

Map enums, strongly typed ids, JSON and value objects in EF Core using value converters, owned entity types and complex types, with runnable stand-ins for the conversion idea.

Databases know a small set of column types: integers, text, dates, booleans, binary. Your domain model knows many more: OrderStatus enums, Money and EmailAddress value objects, CustomerId wrappers, an Address that belongs to a customer. EF Core bridges the gap with two features: value converters, which translate one property to and from a column value, and owned types (and the newer complex types), which store a small object inside its parent's row or table.

This lesson shows when and how to use them, with the real configuration read-only and runnable stand-ins that demonstrate the translation ideas.

Value converters

A value converter is a pair of functions: model to provider (what goes into the column) and provider to model (what comes out). Built-in converters already handle the common cases (enum to int, bool to int, Guid to string). Add your own when the default is not what you want.

Store an enum as readable text instead of a number:

C#
modelBuilder.Entity<Order>()
    .Property(o => o.Status)
    .HasConversion<string>();           // "Shipped" instead of 2

Readable text survives enum reordering, which numbers do not: inserting a new enum member in the middle silently changes the meaning of stored numbers. The cost is a longer column and a string comparison.

A custom converter for a value object:

C#
public readonly record struct Email(string Value);

modelBuilder.Entity<Customer>()
    .Property(c => c.Email)
    .HasConversion(
        email => email.Value,           // to the column
        text => new Email(text))        // from the column
    .HasMaxLength(254);

Strongly typed ids work the same way and stop you from passing a CustomerId where an OrderId is expected:

C#
public readonly record struct OrderId(Guid Value);

modelBuilder.Entity<Order>().Property(o => o.Id)
    .HasConversion(id => id.Value, g => new OrderId(g));

To convert every property of a type, register it in ConfigureConventions: builder.Properties<Email>().HaveConversion<EmailConverter>();.

Two cautions: LINQ can only translate comparisons that go through the converter (comparing a Email property with an Email value works; calling .Value.StartsWith on it may not), and EF Core needs a value comparer for converted mutable types such as lists, so it can tell whether the value changed.

Value converters

To column Model value to storage
From column Storage to model value
Enum as text HasConversion<string>()

Keep domain types rich

1 / 2

Stand-in: converters as plain functions

The stand-in is not EF Core. It builds a tiny Converter<TModel, TProvider> and shows an enum and an email value object travelling to a "column" and back, including what happens when an enum is reordered and numbers are stored.

C# Stand-in: a value converter pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Owned entity types

An owned type is a class that only makes sense as part of another entity, with no identity of its own: an Address of a Customer, a Money inside an Order. By default its properties are stored as columns in the owner's table:

C#
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public Address ShippingAddress { get; set; } = new();
}

public class Address
{
    public string Street { get; set; } = "";
    public string City { get; set; } = "";
    public string PostCode { get; set; } = "";
}

modelBuilder.Entity<Customer>().OwnsOne(c => c.ShippingAddress);

The table Customers gets columns ShippingAddress_Street, ShippingAddress_City and ShippingAddress_PostCode. Queries can filter on them as usual: db.Customers.Where(c => c.ShippingAddress.City == "Oslo").

Variations:

  • OwnsMany stores a collection in its own table with a hidden key (or, on providers with JSON support, in a JSON column via .ToJson()).
  • Rename columns inside OwnsOne(c => c.ShippingAddress, a => { a.Property(x => x.Street).HasColumnName("Street"); }).
  • Two owned properties of the same type (BillingAddress, ShippingAddress) get distinct column prefixes automatically.
  • Owned instances are loaded with the owner; you do not Include them.

Complex types (EF Core 8 and later)

A complex type is a lighter cousin of the owned type: it is a value object with no key and, importantly, value semantics, so it can be shared and compared by value. Configure it with ComplexProperty or mark the class with [ComplexType]:

C#
modelBuilder.Entity<Customer>().ComplexProperty(c => c.ShippingAddress);

Prefer complex types for true value objects (EF Core 8+); owned types remain the choice when you need an owned collection in a separate table or the older behavior. Complex types do not track identity, so two customers can hold equal (or the same) addresses without EF Core complaining.

JSON columns

Where the provider supports it (SQL Server, PostgreSQL, SQLite, MySQL), an owned or complex type can be stored as one JSON column:

C#
modelBuilder.Entity<Customer>().OwnsOne(c => c.Preferences, b => b.ToJson());

You can still query into the JSON with LINQ (c.Preferences.Theme == "dark"), and EF Core translates it to the database's JSON functions. Use it for flexible, rarely joined data; keep core, frequently filtered data in real columns.

Stand-in: flattening an owned type

This stand-in is not EF Core. It flattens a nested Address into prefixed columns, the way an owned type is stored, then rebuilds the object from a row.

C# Stand-in: flatten and rebuild an owned type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Storing enums as numbers and later reordering them. Use HasConversion<string>() or explicit numeric values.
  • Forgetting a value comparer for a converted list or other mutable object, so changes are not detected.
  • Treating owned types as entities: they cannot be queried on their own through a DbSet and are loaded with the owner.
  • Overusing JSON columns: they make filtering, indexing and reporting harder than ordinary columns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a value converter do?

    It is a pair of functions between the model type and the provider (column) type.
  2. 2. Why is storing an enum as text often safer than as a number?

    Numbers depend on the declaration order; names do not.
  3. 3. Where is an owned type stored by default?

    OwnsOne maps the owned properties to columns (prefixed with the navigation name) of the owner's table.
  4. 4. Which is the best fit for a value object compared by value, in EF Core 8 and later?

    Complex types are value objects without identity and with value semantics.

Summary

  • Value converters translate between your types and column types (enums as text, value objects, strongly typed ids).
  • Mutable converted values need a value comparer.
  • Owned types store a part-of object in the owner's row (OwnsOne) or in its own table (OwnsMany).
  • Complex types (EF Core 8+) model value objects without identity.
  • JSON columns suit flexible data; keep hot, filtered data in real columns.

Next: Indexes, Constraints and Default Values