簡體   English   中英

實體框架未在 SQL Server 中創建外鍵

[英]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; }
}

您現在應該在學生表中看到 FK 列SQL 表定義

目前StudentId (PK) 用作引用AddressId (PK) 的外鍵(由於應用了ForeignKey屬性),如下所示:

在此處輸入圖片說明

如果您希望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; }
}

導致以下結構:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM