如何在 EF Core 2.2 中使用支持字段设置只读集合属性

我正在尝试创建一个实体类,它将通过只读属性公开相关集合,如下所示:


public class MyEntity: Entity

{

    public int Id{ get; private set; }

    private IList<RelatedEntity> _relatedEntities = new List<RelatedEntity>();

    public IReadOnlyList<RelatedEntity> RelatedEntities => _relatedEntities.ToList().AsReadOnly();

}

构建器类如下所示:


public void Configure(EntityTypeBuilder<MyEntity> builder)

{

    builder.HasKey(x=>x.Id);

    builder.Property<IReadOnlyList<RelatedEntity>>("RelatedEntities")

        .HasField("_relatedEntities ")

        .UsePropertyAccessMode(PropertyAccessMode.Field);

}

它可以构建,但在运行时崩溃,但有以下例外:


InvalidOperationException:指定字段“_latedEntities”;类型为“IList”;不能用于属性“MyEntity.RelatedEntities”类型为“IReadOnlyList”。只能使用可从属性类型分配的类型的支持字段。


您能提供一个如何处理这个问题的工作示例吗?


摇曳的蔷薇
浏览 272回答 4
4回答

收到一只叮咚

我检查了这个并且它起作用了:private readonly List<RelatedEntity> _relatedEntitys;public IReadOnlyCollection<RelatedEntity> RelatedEntitys => _relatedEntitys;并且配置必须如下所示:&nbsp; &nbsp; builder.HasMany(x => x.RelatedEntitys)&nbsp; &nbsp; &nbsp; &nbsp; .WithOne()&nbsp; &nbsp; &nbsp; &nbsp; .IsRequired()&nbsp; &nbsp; &nbsp; &nbsp; .HasForeignKey(x => x.RelatedEntityId)&nbsp; &nbsp; &nbsp; &nbsp; .OnDelete(DeleteBehavior.Cascade);&nbsp; &nbsp; builder.Metadata&nbsp; &nbsp; &nbsp; &nbsp; .FindNavigation("RelatedEntitys")&nbsp; &nbsp; &nbsp; &nbsp; .SetPropertyAccessMode(PropertyAccessMode.Field);

aluckdog

EF core 要求您使用具体类型作为支持字段。您需要将代码更改为:private&nbsp;readonly&nbsp;List<RelatedEntity>&nbsp;_relatedEntities&nbsp;=&nbsp;new&nbsp;List<RelatedEntity>(); public&nbsp;IReadOnlyList<RelatedEntity>&nbsp;RelatedEntities&nbsp;=>&nbsp;_relatedEntities.ToList();

繁花不似锦

错误消息响亮而清晰:IList 不可分配给 IReadOnlyList将属性类型更改为与支持字段相同的类型即可解决问题。更新:因为 IEnumerable<T> 默认情况下是只读的,我相信这将是您最好的选择。&nbsp; &nbsp; public class MyEntity: Entity&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int Id { get; private set; }&nbsp; &nbsp; &nbsp; &nbsp; private readonly List<RelatedEntity> _relatedEntities = _collection.ToList().AsReadOnly();&nbsp; &nbsp; &nbsp; &nbsp; public IEnumerable<RelatedEntity> RelatedEntities => _relatedEntities;&nbsp; &nbsp; }按如下方式更新您的 Fluent API:&nbsp; &nbsp; builder.HasKey(x=>x.Id);&nbsp; &nbsp; builder.Metadata.FindNavigation("RelatedEntities")&nbsp; &nbsp; &nbsp; &nbsp; .UsePropertyAccessMode(PropertyAccessMode.Field);

牛魔王的故事

对于 EF Core 2,我相信支持字段必须是 HashSet<T> 类型才能被框架正确识别,因此这应该有效:public class MyEntity {   private HashSet<RelatedEntity> _relatedEntities = new HashSet<RelatedEntity>();     public IReadOnlyCollection<RelatedEntity> RelatedEntities => _relatedEntities; }
打开App,查看更多内容
随时随地看视频慕课网APP