您好,登錄后才能下訂單哦!
這篇文章主要介紹了Linq如何定義實(shí)體關(guān)系,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
Linq實(shí)體關(guān)系的定義
比如我們的論壇分類表和論壇版塊表之間就有關(guān)系,這種關(guān)系是1對多的關(guān)系。也就是說一個(gè)論壇分類可能有多個(gè)論壇版塊,這是很常見的。定義Linq實(shí)體關(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的映射沒有什么不同,只是我們還增加了一個(gè)Boards屬性,它返回的是Board實(shí)體集。通過特性,我們定義了關(guān)系外鍵為BoardCategory(Board表的一個(gè)字段)。然后來看看1對多,多端版塊表的實(shí)體:
[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實(shí)體關(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個(gè)的分類-------------<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/>");
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Linq如何定義實(shí)體關(guān)系”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。