'Default values for EF Core with enum to string Value Conversion
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?
Solution 1:[1]
(Improving on vsarunov's answer, which, as mentioned in the comments, doesn't work)
If you do the parsing in a separate method:
private MyEnumType ParseEnum(string input)
{
if (Enum.TryParse<MyEnumType>(input, true, out var res))
return res;
return default;
}
Then you can use it in your converter:
entity.Property(e => e.MyEnumField)
.HasMaxLength(50)
.HasConversion(
v => v.ToString(),
v => ParseEnum(v));
You might prefer, especially if you need to convert several enum types, creating a generic extension method to do the parsing:
public static T ToEnum<T>(this string input) where T : struct
{
if (Enum.TryParse<T>(input, true, out var res))
return res;
return default;
}
Then in your converter:
entity.Property(e => e.MyEnumField)
.HasMaxLength(50)
.HasConversion(
v => v.ToString(),
v => v.ToEnum<MyEnumType>());
Solution 2:[2]
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
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 | |
| Solution 2 | vsarunov |
