Is it possible to define a ValueConversion on a private field?

asp.net-core c# entity-framework entity-framework-core

Question

EF Core lets you specify a private field to use in the database using string syntax:

modelBuilder.Entity<MyEntity>().Property("myField");

And you can specify value conversions for properties:

modelBuilder
    .Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasConversion(
        v => v.ToInt(),
        v => new MyProperty(v));

But is it possible to specify a value conversion for a private field? This doesn't compile, presumably because the type is unknown:

// won't work
modelBuilder.Entity<MyEntity>().Property("myField")
    .HasConversion(
        v => v.ToInt(),
        v => new MyFieldType(v));

Nor can you use the generic type parameter, because those are for predefined value converters provided by EF Core:

// won't work
modelBuilder.Entity<MyEntity>().Property("myField")
    .HasConversion<MyFieldType>(
        v => v.ToInt(),
        v => new MyFieldType(v));

Is it possible to define a ValueConversion on a private field?

1
1
2/7/2019 6:36:00 PM

Accepted Answer

EF Core lets you specify a private field to use in the database using string syntax

It also allows you to specify the property type:

modelBuilder.Entity<MyEntity>()
    .Property<MyFieldType>("myField")
//                 ^

Now all the standard typed value converter fluent APIs work:

.HasConversion(
    v => v.ToInt(),
    v => new MyProperty(v));
2
2/7/2019 6:58:58 PM

Popular Answer

Yes, you just have to define a new ValueConverter first:

ValueConverter<MyFieldType, int> myConverter = new ValueConverter<MyFieldType, int>(
    v => v.ToInt(),
    v => new MyFieldType(v));

modelBuilder.Entity<MyEntity>()
    .Property("myField")
    .HasConversion(myConverter);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow