dotnet / dotnet/efcore

Primitive collections without setters don't get discovered by convention

Open
#34,815 2 comments 0 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-model-building area-primitive-collections breaking-change
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Regular primitive collections (`Ints` in the example) get discovered by convention. However when the collection is backed by a private field, they are not. One needs to explicitly mark them in OnModelCreating. Documentation sort of implies those should be discovered automatically as well: https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-9.0/whatsnew#read-only-primitive-collections

```cs
[ConditionalFact]
public async Task ReproPrimitiveCollections()
{
using var ctx = new MyContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

var works = await ctx.Entities.Where(x => x.Ints.Any(i => i > 0)).ToListAsync();
var fails = await ctx.Entities.Where(x => x.Strings.Any(i => i != "Foo")).ToListAsync();
var alsoFails = await ctx.Entities.Where(x => x.ReadOnlyInts.Any(i => i > 0)).ToListAsync();
}

public class MyContext : DbContext
{
public DbSet Entities { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// uncomment to make the test work
//modelBuilder.Entity().PrimitiveCollection(x => x.Strings);
//modelBuilder.Entity().PrimitiveCollection(x => x.ReadOnlyInts);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ReproPrimitiveCollections;Trusted_Connection=True;MultipleActiveResultSets=true");
}
}

public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }

public List Ints { get; set; }

private readonly List _readOnlyInts = [];
public IReadOnlyList ReadOnlyInts => _readOnlyInts;

private readonly List _strings = [];
public List Strings => _strings;
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.