实体框架未在SQL Server中创建外键

时间:2020-09-12 21:40:39

标签: c# .net entity-framework entity-framework-6 ef-code-first

对于代码优先方法,我有以下几类。我明确声明要让StudentId列成为表Addresses中的外键。

public class Student
{
    [ForeignKey("Address")]
    public int StudentId { get; set;}
    public string StudentName { get; set; }
    public virtual Address Address { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string AddressName { get; set; }

    public virtual Student Student { get; set; }
}

运行迁移时,这是刷新后在SQL Server中看到的内容,学生表中没有外键列。

enter image description here

我该怎么办,原因是什么?

2 个答案:

答案 0 :(得分:1)

ForeignKey属性被分配给StudentId属性。这样会在“学生”表中的“ StudentId”列(也是主键)和“地址”表中的“ AddressId”列之间生成外键关系。

假设您需要一个明确的外键,则应在您的Student类中添加一个AddressId列,并使用ForeignKey属性指定它,如下所示:

 public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public virtual Address Address { get; set; }
    [ForeignKey("Address")]
    public int AddressId { get; set; }
}

您现在应该在“学生”表中看到“ FK”列 SQL Table Definition

答案 1 :(得分:1)

当前StudentId(PK)用作引用AddressId(PK)的外键(由于对其应用了ForeignKey属性) 如下所示:

enter image description here

如果您希望Student表具有一个名为AddressId的附加列(FK)并引用AddressIdAddress表PK),请遵循以下实现需要额外的ForeignKey属性,因为当EF的名称与相关实体的主键属性匹配时,EF会将其作为外键属性)

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int AddressId { get; set; }
    public virtual Address Address { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string AddressName { get; set; }
    public virtual Student Student { get; set; }
}

结果如下:

enter image description here