简体   繁体   中英

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.

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.

在此处输入图片说明

What can I do, what is the reason?

The ForeignKey attribute is assigned to the StudentId property. 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.

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:

 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 tableSQL 表定义

Currently StudentId (PK) is used as a foreign key referring to AddressId (PK) (Due to ForeignKey attribute being applied on it) as demonstrated below:

在此处输入图片说明

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)

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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