I ran into an issue using value conversion, which is new in EF Core 2.1, for List to string conversion.
Since I did not need to be able to filter the List of Enum values in the Database I decided to map my List of Enum Values to a comma delimited string with the int values.
The Conversion should look like this:
From: List<EnumType>{EnumType.Value1, EnumType.Value2}
To: 1,2
Everything seemed to work fine but EF seems not to notice that the list of Enum values was changed and does not issue an update in the database. Is there a limitation that does not allow value conversion for lists?
The Value Conversion Code looks like this:
private const char ENUM_LIST_DELIMITER = ',';
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Entity>().Property(x => x.Types)
.HasConversion(x => ConvertToString(x), x => ConvertToEnumList<EnumType>(x));
}
private static List<TEnum> ConvertToEnumList<TEnum>(string value) where TEnum : struct, IConvertible
{
return value?.Split(ENUM_LIST_DELIMITER)
.Select(Enum.Parse<TEnum>)
.ToList();
}
private static string ConvertToString<TEnum>(IEnumerable<TEnum> value) where TEnum : struct, IConvertible
{
return string.Join(ENUM_LIST_DELIMITER, value.Select(x => Convert.ToInt32(x)));
}
}