linq to sql多表基礎(chǔ)描述
本文主要闡述linq to sql多表關(guān)聯(lián)與動(dòng)態(tài)條件查詢,雖然好多人對(duì)linq很不熟悉,但是本文作者簡(jiǎn)言較簡(jiǎn)單,還是很容易理解的。
在去年的有接觸過(guò)linq,也小試了一刀.但僅僅是簡(jiǎn)單的from并沒(méi)有深入去揣摩.這次正好用MVC開(kāi)發(fā)這套系統(tǒng).所以使用linq 是必須的.
之前我也有說(shuō)過(guò)linq的編寫方式看起來(lái)很拉風(fēng),但他并不是很么的***,有利肯定有弊.要不microsoft推出linq這么長(zhǎng)時(shí)間了.也沒(méi)見(jiàn)市場(chǎng)上很熱門.至今在我看來(lái).用的人還是很少.這次在開(kāi)發(fā)的過(guò)程中.最讓我抓狂的就是linq to sql多表關(guān)聯(lián)與動(dòng)態(tài)條件查詢.
雖然網(wǎng)上有很多資料是linq to sql多表關(guān)系當(dāng)然也有動(dòng)態(tài)條件查詢的.但是并沒(méi)有找到我想要的答案.與是只能靠自己摸索了.下面就是我要實(shí)現(xiàn)的結(jié)果,linq to sql多表關(guān)聯(lián).INNER JOIN + LEFT JOIN
- var q =
- (from ar in db.Articles
- join c in db.Categories on ar.ParentId
- equals c.Id
- join sc in db.Categories on ar.SubId equals sc.Id into scate
- from sc in scate.DefaultIfEmpty()
- where ar.IsPrivate == false
- orderby ar.CreateTime descending
- __select new
- {
- ararticle = ar,
- pcate = c,
- scscate = sc
- }).Take(3);
linq to sql多表動(dòng)態(tài)條件查詢:
- Expression> lambda = ar => (1==1);
- if (id != null)
- lambda = (ar => ar.Id == id);
- var article = db.Articles.OrderByDescending
- (a => a.CreateTime).Where(lambda);
- return View(article);
linq to sql多表,如果你要根據(jù)條件不同顯示相應(yīng)的數(shù)據(jù)的話,只要在q對(duì)像后追加Where()就OK:
- int Record__count = q.Count(); //得到記錄數(shù)
- int page = PagerHelper.GetCurrentPage();
- int SkipIndex = (page-1)__ * 5;
- var q = (from ar in db.Articles
- join c in db.Categories on ar.ParentId
- equals c.Id
- join sc in db.Categories on ar.SubId equals sc.Id into scate
- from sc in scate.DefaultIfEmpty()
- where ar.IsPrivate == false
- orderby ar.CreateTime descending
- __select new
- {
- ararticle = ar,
- pcate = c,
- scscate = sc
- });.Skip(SkipIndex).Take(5);
以上就是對(duì)linq to sql多表的詳細(xì)闡述。
【編輯推薦】