Efcore: Configuring a value converter for a property of an owned type

Created on 3 Oct 2018  路  5Comments  路  Source: dotnet/efcore

Hi all, I'using EF Core 2.1 and I have this value object in my model, which is then configured as an owned type for properties such as "Price".
```C#
public class Money
{
public Currency Currency { get; set; }
public decimal Amount { get; set; }
}

Currency is a simple enum like this.
```C#
public enum Currency
{
  EUR,
  USD,
  GBP
}

I'd like to persist the Currency property as a string, i.e. I want 'EUR' or 'USD' to appear in the database instead of its numerical representation.

For this, I tried to configure the EnumToStringConverter but the fluent interface doesn't seem to allow that. Things I've tried.
C# modelBuilder.Entity<MyEntity>(e => e.Price.Currency).HasConversion... //Doesn't allow complex property expression modelBuilder.Owned<Money>()... //Doesn't have a HasConversion method. modelBuilder.Entity<Money>()... //Doesn't work since this is an owned type and not an entity
How should I do it? I don't want to write a converter for the whole Money object.
Thanks in advance.

closed-question customer-reported

Most helpful comment

@BrightSoul This should work:
C# modelBuilder.Entity<Blog>(c => { c.OwnsOne(e => e.Price, b => { b.Property(e => e.Currency).HasConversion<string>(); }); });

All 5 comments

think you need
c# Entity<MyEntity>().Property(e => e.Price.Currency).HasConversion

@Tarig0 I'd be _really_ surprised if that works. Did you try it?

@BrightSoul This should work:
C# modelBuilder.Entity<Blog>(c => { c.OwnsOne(e => e.Price, b => { b.Property(e => e.Currency).HasConversion<string>(); }); });

Thank you @ajcvickers, it's working wonderfully. I have to repeat that configuration with each usage of the Money type but it's not a big deal right now. Of course, a type-wide converter configuration would be even more useful. Something like this:

modelBuilder.Owned<Money>().Property(money => money.Currency).HasConversion<string>();

Also, I couldn't find any mention in the documentation, maybe a paragraph about owned types would help.
Thanks again!

@BrightSoul I'll file a docs issue. Global config of a converter is tracked by #10784.

Was this page helpful?
0 / 5 - 0 ratings