Reputation: 4074
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?
Upvotes: 0
Views: 1148
Reputation: 6432
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:
Upvotes: 1
Reputation: 56
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 table
Upvotes: 1