Web Api 中相同 table 的外键 2

Foreign key for same table in Web Api 2

我有一个数据模型,它具有通过数据定义的文件夹结构。各种对象可以在这些文件夹中,包括文件夹本身,类似于资源管理器中的文件夹级联和相互包含的方式。

我想我已经弄清楚了外键在这个堆栈中是如何工作的,但是当我把它迁移到数据库时,系统不让我。有什么问题?一定有办法将这些文件夹条目相互嵌套,对吧?

namespace api.Models
{
    public class Folder
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }

        public int SuperFolderId { get; set; }
        public Folder SuperFolder { get; set; }
    }
}

这里的疏忽是自引用外键不能为空。想象一个文件结构,其中每个文件夹都需要一个超级文件夹。它要么永远上升,要么两个文件夹必须相互引用并且它会循环。

这与员工拥有经理的经典自引用关键示例相同,其中经理也在员工 table 上。在到达公司负责人之前,你只能沿着这条链往上走那么远。

系统假定外键不可为空,因此它在不需要 [Required] 属性的情况下使它们成为必需的。有时将外键设置为可选是有效的,为此,您将 int 转换为可为 null 的 int,或 "int?"。下面的代码解决了这个问题。

namespace api.Models
{
    public class Folder
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }

        public int? SuperFolderId { get; set; }
        public Folder SuperFolder { get; set; }
    }
}