简体   繁体   English

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

[英]Entity Framework not creating foreign key in SQL Server

I have these following classes for code first approach.我有以下代码优先方法的类。 I am explicitly declaring that I want columns StudentId to be a foreign key in table Addresses.我明确声明我希望 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; }
}

When I run migration, this is what I see in SQL Server after refreshing, there is no foreign key column in Student's table.我运行migration的时候,刷新后在SQL Server中看到的就是这个,Student表中没有外键列。

在此处输入图片说明

What can I do, what is the reason?我该怎么办,原因是什么?

The ForeignKey attribute is assigned to the StudentId property. ForeignKey 属性分配给 StudentId 属性。 This generate a Foreign Key relation between the StudentId column (which is also the primary key) in Students table and the AddressId column in Address table.这会在 Students 表中的 StudentId 列(也是主键)和 Address 表中的 AddressId 列之间生成外键关系。

Assuming you want an explicit foreign key, you should add a AddressId column to your Student class and designate it with the ForeignKey attribute like this:假设您需要一个显式外键,您应该向 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; }
}

You should now see the FK column in Students table您现在应该在学生表中看到 FK 列SQL 表定义

Currently StudentId (PK) is used as a foreign key referring to AddressId (PK) (Due to ForeignKey attribute being applied on it) as demonstrated below:目前StudentId (PK) 用作引用AddressId (PK) 的外键(由于应用了ForeignKey属性),如下所示:

在此处输入图片说明

Follow the implementation below should you want Student table to have an additional column (FK) named AddressId referring to AddressId ( Address table PK), there is no need for an additional ForeignKey attribute since EF makes a property as foreign key property when its name matches with the primary key property of a related entity)如果您希望Student表有一个名为AddressId的附加列 (FK) 引用AddressIdAddress表 PK),请按照下面的实现,不需要额外的ForeignKey属性,因为 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; }
}

Resulting in the following structure:导致以下结构:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM