Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core 2.1 Value Conversion Update Issue

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)));
}
}
like image 935
Edub Avatar asked May 08 '26 23:05

Edub


1 Answers

Value conversion on List<T> worked for me when using DbContext.Set<T>.Update(entity) instead of getting the entity from the context, changing some properties and then calling .SaveChangesAsync(). This is probably due to what @Ivan Stoev said regarding equality comparison. Update() marks all properties in an entity as changed. Perhaps not desired in all situations, but can be an quick fix.

like image 136
veuncent Avatar answered May 10 '26 22:05

veuncent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!