Default values for EF Core with enum to string Value Conversion

.net c# entity-framework-core enums

Question

EF Core 2.1+ supports Value Conversions. You can use the built-in EnumToStringConverter<> to automatically convert an Enum to string, and vice versa.

I'm connecting to an existing database and would like one of the columns to be converted to an Enum, so EnumToStringConverter<> seems to be right up my alley. However, the database is also outside of my control (I only have read access) so what happens if anyone inserts a row into the table with a string value that does not match any of my enum definitions?

Preferrably I would like any unknown values to be mapped to an Unknown enum value, but I can't find any documentation on how to do this other than to manually create my own ValueConverter object where I implement my own manual parsing of all string values and map them to the appropriate enum value. This seems a bit cumbersome and adds additional maintenance, so I would very much like to have some automation here... meaning that if an unknown string value is found in the database, EFCore automatically maps this to my custom Unknown enum value.

Is this possible?

1
3
12/11/2019 10:40:50 AM

Popular Answer

If I understand you correctly this should do the trick:

 entity.Property(e => e.MyEnumField)
        .HasMaxLength(50)
        .HasConversion(
                v => v.ToString(),
                v => {


                if(Enum.TryParse(v,true,out var res)){
                return res;
                }

                return MyEnum.Default;

                })
               .IsUnicode(false);

I have not tested this.

Source: https://docs.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=netframework-4.8

https://entityframeworkcore.com/knowledge-base/44262314/how-can-i-make-ef-core-database-first-use-enums-

1
12/11/2019 10:18:53 AM


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