[英]Entity Framework not creating foreign key in 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; }
}
我運行migration的時候,刷新后在SQL Server中看到的就是這個,Student表中沒有外鍵列。
我該怎么辦,原因是什么?
ForeignKey 屬性分配給 StudentId 屬性。 這會在 Students 表中的 StudentId 列(也是主鍵)和 Address 表中的 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; }
}
目前StudentId
(PK) 用作引用AddressId
(PK) 的外鍵(由於應用了ForeignKey
屬性),如下所示:
如果您希望Student
表有一個名為AddressId
的附加列 (FK) 引用AddressId
( Address
表 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; }
}
導致以下結構:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.