淺析Linq鏈接
好多開(kāi)發(fā)人員都感覺(jué)Linq連接不是很實(shí)用,筆者倒不這樣認(rèn)為,筆者認(rèn)為在做Linq連接時(shí)只要注意了一些問(wèn)題,Linq連接還是可以實(shí)現(xiàn)的,筆者先寫了一段Linq連接的代碼,還有介紹了Linq連接的注意事項(xiàng)。以下是一段Linq連接的代碼(Group By)。
- SELECT p.ParentId, COUNT(c.ChildId)FROM ParentTable p LEFT OUTER JOIN ChildTable c
- ON p.ParentId = c.ChildParentIdGROUP BY p.ParentId
轉(zhuǎn)換成Linq連接:
- (from p in context.ParentTable
- join c in context.ChildTable
- on p.ParentId equals c.ChildParentId into j1
- from j2 in j1.DefaultIfEmpty()
- select new {
- ParentId = p.ParentId,
- ChildId = j2==null? 0 : 1
- })
- .GroupBy(o=>o.ParentId)
- .Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })
當(dāng)使用連接字符Linq連接本地?cái)?shù)據(jù)庫(kù)時(shí),使用string connectionString = "Server=localhost;uid=sa;pwd=sa;database=DataBase;Integrated Security=SSPI"測(cè)試正常,但連接遠(yuǎn)程數(shù)據(jù)庫(kù)會(huì)拋出“未與信任 SQL Server 連接相關(guān)聯(lián)”錯(cuò)誤。應(yīng)更改連接字符串為:“Data Source=192.168.4.23;Initial Catalog=DataBase;Persist Security Info=True;User ID=sa;Password=sa”測(cè)試通過(guò)。
主要原因在于:
(1)用戶名稱 uid=>User ID;
(2)密碼 pwd=>Password
在使用ADO.Net進(jìn)行數(shù)據(jù)Linq連接時(shí),在字符串格式上,要求不是十分嚴(yán)格,而使用Linq進(jìn)行數(shù)據(jù)庫(kù)訪問(wèn),則要求更嚴(yán)格一些。
順便解釋下連接字符串屬性含義:
關(guān)于Linq連接主要介紹如下兩個(gè)屬性:
Persist Security Info屬性的意思是表示是否保存安全信息,其實(shí)可以簡(jiǎn)單的理解為"ADO.Net在數(shù)據(jù)庫(kù)連接成功后是否保存密碼信息",True表示保存,F(xiàn)alse表示不保存。默認(rèn)為False.
Integrated Security屬性的意思是表示是否使用Windows身份認(rèn)證,Integrated Security = Ture使用windows身份認(rèn)證,但是,只有當(dāng)Integrated Security = SSPI將適用于OleDb .NET Framework 數(shù)據(jù)提供程序。為 ConnectionString 設(shè)置 Integrated Security=true 將引發(fā)異常。
以上就是筆者為你介紹的Linq連接方法及注意問(wèn)題。
【編輯推薦】