How to migrate a list of primitives — EF 7
Feb 6, 2023
My problem was this error that I got while trying to run my migrations:
The idea is that I had an entity that had as a property a “List<string>”, and the SQL EF “driver” doesn’t support out-of-the-box migrations of the list of primitives. (If you’ll use PostgreSql, you won’t have this problem. Actually, this appeared once I moved from Postgre to MS-SQL).
I found the solution after a lot of research directly in the Microsoft documentation (who would have thought…). The URL can be found here.
The code is the next one:
modelBuilder.Entity<MyEntity>()
.Property(e => e.Skills)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions)null),
new ValueComparer<List<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => c.ToList()));