dotnet / dotnet/efcore

Support IReadOnlyList for Complex Collections

Open
#37,405 3 comments 15 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-complex-types area-model-building consider-for-next-release customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### What problem are you trying to solve?

It can be useful to expose collection navigation properties as IReadOnlyList to prevent client code from adding to the list directly. Instead a method is available that can do some validation and then add to the list (private property) directly. For example:

```csharp
using Microsoft.EntityFrameworkCore;

const string connectionString = "Server=localhost;Database=complex-issues;Port=5432;User Id=postgres;Password=postgres;Include Error Detail=true";
var options = new DbContextOptionsBuilder()
.UseNpgsql(connectionString)
.Options;
var dbContext = new AppDbContext(options);
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();

public class Entity
{
public Guid Id { get; init; }
private List _complexEntities = [];
public IReadOnlyList ComplexEntities => _complexEntities.AsReadOnly();

public void AddComplexEntity(ComplexEntity complexEntity)
{
//Some validation
_complexEntities.Add(complexEntity);
}
}

public class ComplexEntity
{
public required string Value { get; init; }
}

public class AppDbContext(DbContextOptions options) : DbContext(options)
{
public DbSet Entities { get; init; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().ComplexCollection(entity => entity.ComplexEntities).ToJson();
}
}
```

This scenario is supported when using `OwnsMany(...).ToJson()`, but when converting to ComplexCollection we receive the following exception:

```
System.InvalidOperationException: The complex collection 'Entity'.'ComplexEntities' is of type 'IReadOnlyList' which does not implement 'IList'.
```

### Describe the solution you'd like

For this scenario to work, so it's easier to convert from Owned entities to Complex entities

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.