微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决实体框架未在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。