2

您好有以下查询,我需要转换为 LINQ(VB.net 10),我正在努力正确分组。

您如何将 LINQ 查询称为在子表 (tblApplicationAccess) 上有一个 where 子句并将结果分组到父表 (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]

实体模型

在此处输入图像描述

更新

好的,我已经让它工作了,但我不知道这是否是最好的方法。我需要创建显式连接吗?这有效率吗?

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
4

1 回答 1

0

当您从 ApplicationAccess 端开始并使用 BussinessUnit Navigation 属性访问 BussinessUnit 实体时,您可以省略 Linq to Entities 查询中的联接。此外,投影将是分层的,而不是平面的。并不是说这样会更有效率。做一些分析,让我们知道!

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
于 2012-09-13T19:09:30.767 回答