在 Entity Framework 中为外键使用 nullable

Using nullable for Foreign Key in Entity Framawork

我在 ASP.NET MVC 项目中使用 EF Code First 方法,我在几个实体上有 PK-FK 关系,如下所示:

public class Staff
{
    public int Id { get; set; }

    //Foreign key for Project
    public int ProjectId { get; set; }

    public virtual Project Project { get; set; }
}



public class Project
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Staff> Staffs { get; set; }
}

另一方面,有时需要使用可为空的 FK 值,在这种情况下,我将虚拟记录创建为 N/A,因为需要 FK 属性,这看起来很丑:(我知道我可以轻松地为相关的 FK 属性 使用可空值,但我不确定这是否是一个好方法。使用这种方法的优缺点是什么(我知道所需的 FK 的优点: 数据完整性:)

其次,我应该为可为空的外键使用 0 还是空值?为什么?

添加虚拟记录是不对的,这里正确的做法是使用外键关系int?see here:

If the data type of GradeId is nullable integer, then it will create a null foreign key.

public class Student 
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int? GradeId { get; set; }
    public Grade Grade { get; set; } 
}

The above code snippet will create a nullable GradeId column in the database because we have used Nullable<int> type (? is a shortcut for Nullable<int>)

另一种方法是从工作人员中删除 ProjectId(上述文档中的约定 3):

public class Staff
{
    public int Id { get; set; }
    public virtual Project Project { get; set; }
}

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Staff> Staffs { get; set; }
}