Linq實體關(guān)系簡單概述
本文向大家介紹Linq實體關(guān)系,可能好多人還不了解Linq實體關(guān)系,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
Linq實體關(guān)系的定義
比如我們的論壇分類表和論壇版塊表之間就有關(guān)系,這種關(guān)系是1對多的關(guān)系。也就是說一個論壇分類可能有多個論壇版塊,這是很常見的。定義Linq實體關(guān)系的優(yōu)勢在于,我們無須顯式作連接操作就能處理關(guān)系表的條件。
首先來看看分類表的定義:
- [Table(Name = "Categories")]
- public class BoardCategory
- {
- [Column(Name = "CategoryID", DbType = "int identity",
IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]- public int CategoryID { get; set; }
- [Column(Name = "CategoryName", DbType = "varchar(50)", CanBeNull = false)]
- public string CategoryName { get; set; }
- private EntitySet<Board> _Boards;
- [Association(OtherKey = "BoardCategory", Storage = "_Boards")]
- public EntitySet<Board> Boards
- {
- get { return this._Boards; }
- set { this._Boards.Assign(value); }
- }
- public BoardCategory()
- {
- this._Boards = new EntitySet<Board>();
- }
- }
CategoryID和CategoryName的映射沒有什么不同,只是我們還增加了一個Boards屬性,它返回的是Board實體集。通過特性,我們定義了關(guān)系外鍵為BoardCategory(Board表的一個字段)。然后來看看1對多,多端版塊表的實體:
- [Table(Name = "Boards")]
- public class Board
- {
- [Column(Name = "BoardID", DbType = "int identity", IsPrimaryKey = true,
IsDbGenerated = true, CanBeNull = false)]- public int BoardID { get; set; }
- [Column(Name = "BoardName", DbType = "varchar(50)", CanBeNull = false)]
- public string BoardName { get; set; }
- [Column(Name = "BoardCategory", DbType = "int", CanBeNull = false)]
- public int BoardCategory { get; set; }
- private EntityRef<BoardCategory> _Category;
- [Association(ThisKey = "BoardCategory", Storage = "_Category")]
- public BoardCategory Category
- {
- get { return this._Category.Entity; }
- set
- {
- this._Category.Entity = value;
- value.Boards.Add(this);
- }
- }
- }
在這里我們需要關(guān)聯(lián)分類,設(shè)置了Category屬性使用BoardCategory字段和分類表關(guān)聯(lián)。
Linq實體關(guān)系的使用
好了,現(xiàn)在我們就可以在查詢句法中直接關(guān)聯(lián)表了(數(shù)據(jù)庫中不一定要設(shè)置表的外鍵關(guān)系):
- Response.Write("-------------查詢分類為1的版塊-------------<br/>");
- var query1 = from b in ctx.Boards where b.Category.CategoryID == 1 select b;
- foreach (Board b in query1)
- Response.Write(b.BoardID + " " + b.BoardName + "<br/>");
- Response.Write("-------------查詢版塊大于2個的分類-------------<br/>");
- var query2 = from c in ctx.BoardCategories where c.Boards.Count > 2 select c;
- foreach (BoardCategory c in query2)
- Response.Write(c.CategoryID + " " + c.CategoryName + " " + c.Boards.Count + "<br/>");
【編輯推薦】