How to migrate a list of primitives — EF 7

--

My problem was this error that I got while trying to run my migrations:

The entity type ‘List<string>’ requires a primary key to be defined. If you intended to use a keyless entity type, call ‘HasNoKey’ in ‘OnModelCreating’. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

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()));

--

--

Cosmin Vladutu
Cosmin Vladutu

Written by Cosmin Vladutu

Software Engineer | Azure & .NET Full Stack Developer | Leader

No responses yet