EF Code First中的主外鍵約定和一對一、一對多關系的實現


對於主外鍵約定的理解,其實是學習實體間一對一和一對多關系的基礎。

1.1 主鍵(Key)約定

主鍵的默認約定是:只要字段名為--實體名(類名)+"id"(不區分大小寫),這就算是默認的主鍵約定。

如果要顯示標識的話,就使用特性標簽進行標識:

public class Student
{
    [Key]
    public int StudentKey { get; set; }
    public string StudentName { get; set; }
}

這樣標識的主鍵,在數據庫的名稱就是StudentKey

2.1 外鍵(ForeignKey)約定

外鍵約定稍微復雜一些,主要分為三種形式的顯示指定外鍵和默認的外鍵約定。在一對一關系中比較簡單,在一對多關系中約定規則多一些。

2.1.1 一對一關系中的外鍵約定

在文檔中,這種叫做One-to-Zero-or-One Relationship,這種關系必須手動指定主從表,因為在一個一對一關系中,系統是沒法推測出來誰是主表誰是從表的,而且因為從表的主鍵也是主表的主鍵,也是從表的外鍵,所以沒有必要和多對多關系那樣,指定一個字段作為外鍵,或者為外鍵設置一個友好字段名,這些都是不需要的。

EF中的一對一關系實現如下:

 public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }
}
     
public class StudentAddress 
{
    [ForeignKey("Student")]
    public int StudentAddressId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }

    public virtual Student Student { get; set; }
}

2.1.2 一對一關系的Fluent API實現

欠着

2.2.1 一對多關系中的外鍵約定

默認約定:

默認約定,只需要兩個導航屬性就能實現,student中會根據兩個表名,把standard表的主鍵作為student的外鍵生成一個長名。

 public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    //public int StandardId { get; set }
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
}

當然如果覺得系統生成的名稱不友好,我們可以自己設置外鍵的名字,其中默認的配置規則是entity中如果有字段是導航屬性的名稱+id(不區分大小寫),即把這個字段設置成外鍵。

顯示指定

當然我們可以使用特性標簽[ForeignKey]來指定某個字段作為外鍵:

    [ForeignKey("Standard")]
    public int StandardRefId { get; set; }

這樣的話,外鍵名稱就叫StandardRefId。

我們也可以把標簽屬性放在導航屬性,指定某個字段作為被特性標簽修飾的導航屬性在當前實體的外鍵。

    [ForeignKey("StandardRefId")]
    public Standard Standard { get; set; }

最后一種,我們可以在主表的導航屬性上,也就是字表的ICollection集合上,用特性標簽指定外鍵:

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    [ForeignKey("StandardRefId")]
    public ICollection<Student> Students { get; set; }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM