self-references 在实体中 class DataAnnotations 核心 2.0

self-references in an entity class DataAnnotations core 2.0

我正在尝试将其转换为 DataAnnotations

HasOptional(x => x.ParentEntity)
.WithMany(parentEntity => parentEntity.childrenEntities)
.HasForeignKey(childrenEntity => childrenEntity.ParentEntityId)
.WillCascadeOnDelete(false);

这是我的问题,我有一个引用自身的实体。

public class Product
{
    [Key]
    public int ProductId {get; set;}
    public int? ProductParentId {get; set;}
    [ForeignKey("ProductParentId")]
    [InverseProperty("childrenProducts")]
    public virtual Product ParentProduct { get; set; }
    [ForeignKey("ProductParentId")]
    public virtual List<Products> childrenProducts{ get; set; }
}

但我不断收到错误消息,指出使用 InversePropertyAttribute 和 ForeignKeyAttribute 指定的关系无效并且值不同。

这是我的 table:

产品Table

ProductId   ProductName ProductParentId 
1           Test        Null
2           Test 1      1
3           Test 2      1

我期待的是获得产品及其 children,有什么方法可以实现吗?

提前谢谢你。

外键不属于列表。改用 InverseProperty

[InverseProperty("ParentProduct")]
public virtual List<Products> childrenProducts{ get; set; }