paul.samways.id.au

TIL: Query JSON collections with EF Core

EF Core can map a collection of simple values, such as a List<string> of tags, using PrimitiveCollection:

builder.PrimitiveCollection(x => x.Tags)
  .HasColumnName("tags")
  .IsRequired();

This gives EF Core the collection element metadata needed to query individual values. For example, find content tagged dotnet with:

var results = await db.Content
  .Where(x => x.Tags.Contains("dotnet"))
  .ToListAsync();

With SQLite, the collection is stored as a JSON array, and EF Core translates Contains using json_each. This keeps the filtering in the database without writing SQL by hand.