How to setup readonly collection property with backing field in EF Core 2.2

c# dbcontext entity-framework-core

Question

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 ?

1
0
9/21/2019 6:34:21 PM

Popular Answer

I ckeck this and it worked:

private readonly List<RelatedEntity> _relatedEntitys;
public IReadOnlyCollection<RelatedEntity> RelatedEntitys => _relatedEntitys;

And configuration must be like below:

    builder.HasMany(x => x.RelatedEntitys)
        .WithOne()
        .IsRequired()
        .HasForeignKey(x => x.RelatedEntityId)
        .OnDelete(DeleteBehavior.Cascade);

    builder.Metadata
        .FindNavigation("RelatedEntitys")
        .SetPropertyAccessMode(PropertyAccessMode.Field);
0
3/21/2020 7:20:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow