2

Using EF Core I can tell the modelBuilder to save properties having of enum type as string:

modelBuilder
    .Entity<MyEntity>()
    .Property(e => e.SomeEnumProperty)
    .HasConversion<string>();

This has been asked and answered several times and is also described in the official docs.

However, the list of entitiy types (modelBuilder.Model.GetEntityTypes()) and their subtypes used in my project is rather lengthy and I image it to be error prone to loop over all managed entities, get their properties and their children properties recursivly via reflection and kind of semi-manually add the string conversion.

Is there a builtin way to automatically save all enum property values as strings using the StringEnumConverter?

koks der drache
  • 1,398
  • 1
  • 16
  • 33

1 Answers1

1

Currently (EF Core 3.1.7) there is no other way than the one described in EF CORE 2.1 HasConversion on all properties of type datetime.

The difference here is the way of identifying Enum type properties, and due to the lack of easy public way of getting entity type builder (this property builder), the direct usage of SetProviderClrType metadata API instead of more intuitive HasConversion:

foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
    foreach (var property in entityType.GetProperties())
    {
        var propertyType = Nullable.GetUnderlyingType(property.ClrType) ?? property.ClrType;
        if (propertyType.IsEnum)
            property.SetProviderClrType(typeof(string));
    }
}

This must be at the end of your OnModelCreating override, or more specifically, after all entity types have been discovered.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • Thanks for your answer! After reading the other (datetime related) thread you linked, it seems to me, that what you describe is the best approach available as of today. However, it doesn't feel right to mark it as "correct answer" since the question explicitly asked for a solution _without_ looping the types. So for a correct answer we'll have to wait for a future relase. – koks der drache Sep 03 '20 at 04:39
  • 1
    Like this **Note** in the [official documentation](https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions#the-valueconverter-class): *"There is currently no way to specify in one place that every property of a given type must use the same value converter. This feature will be considered for a future release."*? I can easily copy/paste the above reference as an "answer", but then the whole Q/A makes no sense to me :) Anyway, technically you are right of course. – Ivan Stoev Sep 03 '20 at 05:05