淺析Linq鏈接
好多開發(fā)人員都感覺Linq連接不是很實用,筆者倒不這樣認為,筆者認為在做Linq連接時只要注意了一些問題,Linq連接還是可以實現(xiàn)的,筆者先寫了一段Linq連接的代碼,還有介紹了Linq連接的注意事項。以下是一段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) })
當使用連接字符Linq連接本地數(shù)據(jù)庫時,使用string connectionString = "Server=localhost;uid=sa;pwd=sa;database=DataBase;Integrated Security=SSPI"測試正常,但連接遠程數(shù)據(jù)庫會拋出“未與信任 SQL Server 連接相關(guān)聯(lián)”錯誤。應更改連接字符串為:“Data Source=192.168.4.23;Initial Catalog=DataBase;Persist Security Info=True;User ID=sa;Password=sa”測試通過。
主要原因在于:
(1)用戶名稱 uid=>User ID;
(2)密碼 pwd=>Password
在使用ADO.Net進行數(shù)據(jù)Linq連接時,在字符串格式上,要求不是十分嚴格,而使用Linq進行數(shù)據(jù)庫訪問,則要求更嚴格一些。
順便解釋下連接字符串屬性含義:
關(guān)于Linq連接主要介紹如下兩個屬性:
Persist Security Info屬性的意思是表示是否保存安全信息,其實可以簡單的理解為"ADO.Net在數(shù)據(jù)庫連接成功后是否保存密碼信息",True表示保存,F(xiàn)alse表示不保存。默認為False.
Integrated Security屬性的意思是表示是否使用Windows身份認證,Integrated Security = Ture使用windows身份認證,但是,只有當Integrated Security = SSPI將適用于OleDb .NET Framework 數(shù)據(jù)提供程序。為 ConnectionString 設(shè)置 Integrated Security=true 將引發(fā)異常。
以上就是筆者為你介紹的Linq連接方法及注意問題。
【編輯推薦】