'EF Core domain-wide value conversion for (nested) owned types

I have several value objects (DDD paradigm) set up in EF Core as Owned Types.

EF Core supports configuring owned types in a way that it will automatically treat all references to the given type as an owned type, via the Owned() method.

However, I cannot seem to find a way to specify their configuration, especially value conversion, in a similar, centralized manner.

    {   // Configure value objects as owned types.
        builder.Owned(typeof(Money));
        builder.Owned(typeof(Currency));
        builder.Owned(typeof(Address));
        builder.Owned(typeof(Mass));
        builder.Owned(typeof(MassUnit));

        // Store and restore mass unit as symbol.
        builder.Entity<Product>()
            .OwnsOne(p => p.Mass, c => c.Property(m => m.Unit)
                .HasConversion(
                    u => u.Symbol,
                    s => MassUnit.FromSymbol(s))
                .HasMaxLength(3)
            );
    }

As you can see above, there is a value conversion configured for MassUnit, which is a Value Object nested in Mass.

But I'd have to do this manually for all places where the value objects are used. For example I'm already using the Money type at 3 distinct places, and this type contains Currency, for which I'd wish to configure a similar value conversion.

Is there any (good) way to specify general, domain-wide configuration for the owned types?

I already tried to configure them through builder.Entity<Mass>().Property(m => m.Unit).HasConversion(..), but it seems that EF Core throws if you try to configure an owned type via Entity<>.



Solution 1:[1]

This is possible using a shared ValueConverter:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var converter = new ValueConverter<EquineBeast, string>(
        v => v.ToString(),
        v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v));

    modelBuilder
        .Entity<Rider>()
        .Property(e => e.Mount)
        .HasConversion(converter);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lonix