Skip to main content
 首页 » 编程设计

c#之如何建模自引用对象类型

2024年02月20日10cmt

假设我有一个类 Box:

public class Box 
{ 
    [Required] 
    [Key] 
    int BoxId { get; set; } 
    string BoxName { get; set; } 
} 

我希望能够将盒子添加到其他盒子 - 一个盒子可以有很多盒子或属于一个盒子,但两者都不需要。

我试图在我的项目中像这样建模:

public class Box 
{ 
    [Required] 
    [Key, ForeignKey("ParentBox")] 
    int BoxId { get; set; } 
    string BoxName { get; set; } 
    int ParentBoxId { get; set; } 
    Box ParentBox { get; set; } 
    List<Box> Boxes {get; set;} 
} 

但是我在 this question 中解决了以下错误:

Unable to determine the principal end of the 'App.Core.Set_ParentSet' relationship. Multiple added entities may have the same primary key.

删除 ForeignKey 属性让我可以构建数据库,但是级联删除不起作用。

我不想为 ChildBox 或 ParentBox 创建不同的类,因为在我的应用程序中,一个框是否属于/是否有框会一直发生变化。

在 EF 中对此建模的正确方法是什么?

请您参考如下方法:

试试这个。

public class Box 
{ 
    [Required] 
    [Key] 
    public int BoxId { get; set; } 
 
    public string BoxName { get; set; } 
 
    public int ParentBoxId { get; set; } 
 
    // The foreign key for the Box that points at ParentBox.BoxId  (the [Key]) 
    [ForeignKey("ParentBoxId")] 
    public Box ParentBox { get; set; } 
 
    // The foreign key for the Boxes that point at this.BoxId (the [Key]) 
    [ForeignKey("ParentBoxId")] 
    public virtual ICollection<Box> Boxes {get; set;} 
}