I am trying to create an entity class which will expose a related collection through a readonly property, like this:
public class MyEntity: Entity
{
public int Id{ get; private set; }
private IList<RelatedEntity> _relatedEntities = new List<RelatedEntity>();
public IReadOnlyList<RelatedEntity> RelatedEntities => _relatedEntities.ToList().AsReadOnly();
}
The builder class looks like this:
public void Configure(EntityTypeBuilder<MyEntity> builder)
{
builder.HasKey(x=>x.Id);
builder.Property<IReadOnlyList<RelatedEntity>>("RelatedEntities")
.HasField("_relatedEntities ")
.UsePropertyAccessMode(PropertyAccessMode.Field);
}
It builds but crashes at runtime with the exception:
InvalidOperationException: The specified field '_relatedEntities' of type 'IList' cannot be used for the property 'MyEntity.RelatedEntities ' of type 'IReadOnlyList'. Only backing fields of types that are assignable from the property type can be used.
Could you provide a working example how to deal with this issue ?