【问题标题】:Using nullable for Foreign Key in Entity Framawork在实体框架中使用可为空的外键
【发布时间】:2019-09-09 17:39:41
【问题描述】:

我在 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 的优点:数据完整性:)

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

【问题讨论】:

  • 如果您想让 ProjectId 可选/可为空,只需将数据类型更改为 int?这与 Nullable 相同,并且应该使数据库中的该列允许空值。这对于外键来说很好。
  • @Jon 感谢乔恩的回复。我的第二个问题呢? 对于可为空的 FK,我应该使用 0 还是 null 值?为什么?
  • 始终为空。 0 不起作用,它会给你一个 SQL 外键冲突错误,因为没有 ID 为 0 的项目。
  • 在外键列上使用空值是推荐的方式。这没有缺点。
  • @Jon 再次感谢您的热心帮助...投票赞成。

标签: c# sql-server asp.net-mvc entity-framework entity-framework-6


【解决方案1】:

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

如果GradeId的数据类型是可为空的整数,那么它将创建一个 空外键。

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

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

上面的代码 sn -p 将在 数据库,因为我们使用了Nullable&lt;int&gt; 类型(?Nullable&lt;int&gt;)

另一种方法是从员工中删除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; }
}

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2016-06-18
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多