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

问题描述

对于代码优先方法,我有以下几类。我明确声明要让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

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

解决方法

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

,

当前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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...