4 回答
TA贡献1821条经验 获得超4个赞
我检查了这个并且它起作用了:
private readonly List<RelatedEntity> _relatedEntitys;
public IReadOnlyCollection<RelatedEntity> RelatedEntitys => _relatedEntitys;
并且配置必须如下所示:
builder.HasMany(x => x.RelatedEntitys)
.WithOne()
.IsRequired()
.HasForeignKey(x => x.RelatedEntityId)
.OnDelete(DeleteBehavior.Cascade);
builder.Metadata
.FindNavigation("RelatedEntitys")
.SetPropertyAccessMode(PropertyAccessMode.Field);
TA贡献1847条经验 获得超7个赞
EF core 要求您使用具体类型作为支持字段。您需要将代码更改为:
private readonly List<RelatedEntity> _relatedEntities = new List<RelatedEntity>(); public IReadOnlyList<RelatedEntity> RelatedEntities => _relatedEntities.ToList();
TA贡献1851条经验 获得超4个赞
错误消息响亮而清晰:
IList 不可分配给 IReadOnlyList
将属性类型更改为与支持字段相同的类型即可解决问题。
更新:
因为 IEnumerable<T> 默认情况下是只读的,我相信这将是您最好的选择。
public class MyEntity: Entity
{
public int Id { get; private set; }
private readonly List<RelatedEntity> _relatedEntities = _collection.ToList().AsReadOnly();
public IEnumerable<RelatedEntity> RelatedEntities => _relatedEntities;
}
按如下方式更新您的 Fluent API:
builder.HasKey(x=>x.Id);
builder.Metadata.FindNavigation("RelatedEntities")
.UsePropertyAccessMode(PropertyAccessMode.Field);
TA贡献1830条经验 获得超3个赞
对于 EF Core 2,我相信支持字段必须是 HashSet<T>
类型才能被框架正确识别,因此这应该有效:
public class MyEntity { private HashSet<RelatedEntity> _relatedEntities = new HashSet<RelatedEntity>(); public IReadOnlyCollection<RelatedEntity> RelatedEntities => _relatedEntities; }
- 4 回答
- 0 关注
- 225 浏览
添加回答
举报