Course contentsShow
← C#
Lesson 1035 of 1,90810. Entity Framework Core ModelingFree lesson

Value Conversion for Custom Types

Transform complex domain types into database-compatible formats during persistence.

Value Conversion for Custom Types

In this lesson, you will learn how to map complex domain objects to database-friendly primitives using EF Core Value Converters.

The Problem: Domain Objects vs. Database Columns

In your domain model, you often use rich types like Money, Coordinates, or EmailAddress to ensure type safety and encapsulate logic. However, databases don't natively understand these custom C# classes—they prefer simple types like decimal, string, or int.

Instead of cluttering your domain model with database-specific properties, you can use a Value Converter to bridge this gap. This tells EF Core how to translate your object into a database column when saving, and how to reconstruct the object when querying.

Implementing a Value Converter

Imagine you have a Currency class that holds a string code (e.g., "USD"). Rather than storing the whole object as a JSON blob, you can convert it to a simple string column. You configure this within your DbContext using the Fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(p => p.PriceCurrency)
        .HasConversion(
            v => v.Code,            // Convert to string for the DB
            v => new Currency(v)    // Convert back to object from DB
        );
}

The first lambda expression dictates how the property should be stored (the "write" path), and the second defines how to instantiate your object from the retrieved data (the "read" path).

Why Use This?

This technique is powerful because it keeps your database schema clean and your domain model expressive. You don’t need to force your entities to store raw primitive types, and you don’t need to create "persistence-only" classes that break your domain design. By centralizing this logic in your mapping configuration, the conversion remains transparent to the rest of your application code—your services simply interact with the Currency object, while EF Core handles the heavy lifting of persistence.

Key Takeaway: Use Value Converters to map complex domain types to simple database primitives, allowing you to maintain a clean, rich domain model without sacrificing database compatibility.