2012-09-13 446 views
2

喜有以下查詢,我需要轉換爲LINQ(VB.net 10),我掙扎着爬分組的權利。轉換TSQL到LINQ

你怎麼稱之爲LINQ查詢有一個地方的孩子(tblApplicationAccess)和組對父表(tblBusinessUnit)結果的條款?

TSQL

SELECT tblBusinessUnit.ID, tblBusinessUnit.Name 
    FROM tblBusinessUnit INNER JOIN tblApplicationAccess ON 
     tblBusinessUnit.ID = tblApplicationAccess.BUID 
    WHERE(tblApplicationAccess.ApplicationID = @AppID) 
    GROUP BY tblBusinessUnit.ID, tblBusinessUnit.Name ORDER BY [Name] 

實體模型

enter image description here

更新

OK,我已完成了工作,但我不知道這是否是最好 這樣做的方法。我是否需要創建顯式連接?這是否有效?

Dim var = (From bu In hf.BusinessUnits 
      Join app In hf.ApplicationAccesses On bu.ID Equals app.BUID 
      Where app.ApplicationID.Equals(56) 
      Group By bu.ID, bu.Name, bu.IsInternalSupplier Into Group 
       Select New BusinessUnitModel With {.ID = ID, 
        .Name = Name, 
        .IsInternalSupplier = IsInternalSupplier}).ToList 
+0

你使用LINQ2SQL還是EF? –

+0

實體框架4 –

+0

在我看來,該組是沒有必要的,你只是希望結果按名稱排序,不是嗎? – Dabblernl

回答

0

可以省略,當你開始在ApplicationAccess側LINQ的聯接到實體查詢和使用BussinessUnit導航屬性來獲取到BussinessUnit實體。此外,投影將分層而不是平面。這並不是說這會更有效率。做一些分析並告訴我們!

Using context = New QuerySpikesdfEntities 

    'Create the query using LINQ to Entities. No join is necessary as we use the Navigation property 'BussinessUnit' 
    Dim projections = From entry In context.ApplicationAccessEntries 
         Where entry.ApplicationID = 56 
         Group By supplierKey = entry.BussinessUnit.IsInternalSupplier Into supplierGroup = Group 
         Select New With { 
         .IsInternalSupplier = supplierKey, 
         .Suppliers = From supplier In supplierGroup 
             Order By supplier.BussinessUnit.Name 
             Select New With 
             { 
              .ID = supplier.BussinessUnit.ID, 
              .Name = supplier.BussinessUnit.Name 
             } 
          } 

    'It remains to be seen if the resulting query is more efficient than the one that used the Join 
    'This will output the query to the Console. 
    'Profile this query and the Join query using the Stopwatch class. 
    Console.WriteLine(DirectCast(projections, ObjectQuery).ToTraceString) 

    Console.ReadLine() 

    Console.WriteLine("All Bussiness units that have had access through application with id: {0}", 56) 
    For Each projection In projections 
     Console.WriteLine(" Internal suppliers: {0}", projection.IsInternalSupplier) 
     For Each supplier In projection.Suppliers 
     Console.WriteLine("  ID: {0}, Name: {1}", supplier.ID, supplier.Name) 
     Next 
    Next 

End Using