LINQ to SQL映射關系概述
LINQ to SQL有很多值得學習的地方,這里我們主要介紹LINQ to SQL映射關系,包括介紹LINQ to SQL映射關系Demo等方面。
LINQ to SQL映射關系
在 LINQ to SQL 中,數據庫關聯(如外鍵到主鍵關系)是通過應用 AssociationAttribute 屬性表示的。
可以在您的實體類中將始終相同的任何數據關系編碼為屬性引用。例如,在 Northwind 示例數據庫中,由于客戶通常會下訂單,因此在模型中客戶與其訂單之間始終存在關系。
LINQ to SQL 定義了 AssociationAttribute 屬性來幫助表示此類關系。此屬性與 EntitySet 和 EntityRef 類型一起使用,來表示將作為數據庫中的外鍵關系的內容。
◆EntitySet :為 LINQ to SQL 應用程序中的一對多關系和一對一關系的集合方提供延遲加載和關系維護。
◆EntityRef:為 LINQ to SQL 應用程序中的一對多關系的單一實例方提供延遲加載和關系維護。
大多數關系都是一對多關系,這一點在本主題后面部分的示例中會有所體現。您還可以按如下方式來表示一對一和多對多關系:
◆一對一:通過向雙方添加 EntitySet<(Of <(TEntity>)>) 來表示此類關系。
例如,假設有一個 Customer-SecurityCode 關系,創建此關系的目的是使得在 Customer 表中找不到客戶的安全碼,而只有得到授權的人才能訪問此安全碼。
◆多對多:在多對多關系中,鏈接表(也稱作聯接表)的主鍵通常由來自其他兩個表的外鍵組合而成。
例如,假設有一個通過使用鏈接表 EmployeeProject 構成的 Employee-Project 多對多關系。LINQ to SQL 要求使用以下三個類對這種關系進行模型化: Employee、Project 和 EmployeeProject。在這種情況下,更改 Employee 和 Project 之間的關系似乎需要更新主鍵 EmployeeProject。但是,這種情況***的模型化處理方法是刪除現有 EmployeeProject,然后創建新的 EmployeeProject。
LINQ to SQL映射關系Demo
- [Table(Name = "Student")]
- public class Student
- {
- [Column(IsPrimaryKey = true)]
- public int ID;
- [Column]
- public string StuName;
- [Column]
- public bool Sex;
- [Column]
- public int Age;
- private EntitySet _Scores;
- [Association(Storage = "_Score", OtherKey = "StudentID")]
- public EntitySet Scores
- {
- get { return this._Scores; }
- set { this._Scores.Assign(value); }
- }
- }
- [Table(Name = "Score")]
- public class Score
- {
- [Column(IsPrimaryKey = true)]
- public int ID;
- [Column]
- public int StudentID;
- [Column]
- public float Math;
- [Column]
- public float Chinese;
- [Column]
- public float English;
- [Column]
- public DateTime Times;
- }
【編輯推薦】