我正试图弄清楚如何在VB.NET下的LINQ查询中使用Group Joins。出于某种原因,我似乎在语法上找到的每个例子都是错误的!至少,这是我的编译器一直告诉我的。究竟我在这里做错了什么?
这是一个简单的例子,我想将订单连接到他们的订单商品,这样我最终会得到一个类型,其中包含按orderId组合在一起的订单商品集合:
Dim groupedOrders = (From o In orders
Group Join i In orderItems On o.OrderId Equals a.OrderId Into myOrders
Select o.OrderId, myOrders).ToList()
我在这个例子中遇到的是'myOrders'组我正在创建错误:
在此上下文中无法访问方法'myOrders'的定义。
答案 0 :(得分:4)
在VB中,Into别名需要是“Group”而不是myOrders。使用northwind,您可以按如下方式说明您的查询:
Dim groupedOrders =
From o On Orders
Group Join od in Order_Details On o.OrderID Equals od.OrderID Into Group
Select o.OrderID, Details = Group
如果您想将该组别名为别名,可以使用:
Dim groupedOrders =
From o On Orders
Group Join od in Order_Details On o.OrderID Equals od.OrderID Into GroupedDetails = Group
Select o.OrderID, GroupedDetails
话虽如此,如果您的订单和orderItem来自数据库提供者,您可以使用自然关联而不需要连接:
Dim groupedOrders =
From o In Orders
Select o.OrderID, Details = o.Order_Details
此外,如果您只需要按外键分组,则不需要父表:
Dim groupedOrders =
From od In Order_Details
Group od By Key = od.OrderID Into Group
select Key, Group
答案 1 :(得分:2)
你很亲密。您只需将myOrders
指定为Group
:
Dim groupedOrders = (From o In orders
Group Join i In orderItems On o.OrderId Equals a.OrderId
Into myOrders = Group
Select o.OrderId, myOrders).ToList()
您可以在此MSDN页面中看到类似的示例,包括如何获取论坛的Count
:Introduction to LINQ in Visual Basic。
答案 2 :(得分:0)
我想提供一个LINQ查询的另一个示例,如果不回答这个问题,那么只是为了保留一个副本,以后我可以参考它:
Dim result As List(Of Reception_Users)
result = (From recept In MyBase.QueryGlobalStatic(Of HACRECEP)(Function(x) True)
Join sys In MyBase.QueryGlobalStatic(Of SYSESSIO)(Function(x) True) On recept.IdLocking Equals sys.Id
Join SYUSRG In MyBase.QueryGlobalStatic(Of SYUser)(Function(x) True) On sys.cle_user Equals SYUSRG.Id
Group By SYUSRG.Code, SYUSRG.Nom, SYUSRG.Prenom
Into Groupuser = Group
Select New Reception_Users With
{
.CodeUsager = Code,
.Nom = Nom,
.Prenom = Prenom
}).ToList()
其中MyBase.QueryGlobalStatic()是来自我的上下文的函数,以便允许我将这种代码放置在任何地方而无需检查连接或身份验证数据(除其他外)。等效的内容如下:
result = (From recept In dbContext.HACRECEPs
Join sys In dbContext.SYSESSIOs On recept.IdLocking Equals sys.Id
Join SYUSRG In dbContext.SYUsers On sys.cle_user Equals SYUSRG.Id
Group By SYUSRG.Code, SYUSRG.Nom, SYUSRG.Prenom
Into Groupuser = Group
Select New Reception_Users With
{
.CodeUsager = Code,
.Nom = Nom,
.Prenom = Prenom
}).ToList()