SQL进入LINQ ......需要在正确的方向上轻推

时间:2012-02-27 06:36:52

标签: sql vb.net linq translate

我想使用LINQ作为DataGrivdView数据源...我有正确的SQL查询,但我有一点时间在LINQ中重写它...

SQL:

SELECT ICITEM.ITEMNO, ICITEM.[DESC], MAX(PORCPL.DTARRIVAL) AS Expr1
FROM   ICITEM INNER JOIN
        PORCPL ON PORCPL.ITEMNO = ICITEM.ITEMNO
WHERE  (ICITEM.ITEMNO LIKE '%R001%')
GROUP BY ICITEM.ITEMNO, ICITEM.[DESC]

我在LINQ的微弱尝试:

    Dim s = From items In db.ICITEMs
    Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
    Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
    Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = recDates.DTARRIVAL

我的LINQ日志...

SELECT [t0].[ITEMNO] AS [Item_ID], [t0].[DESC] AS [Description], [t1].[DTARRIVAL] AS [rd]
FROM [dbo].[ICITEM] AS [t0]
INNER JOIN [dbo].[PORCPL] AS [t1] ON [t0].[ITEMNO] = [t1].[ITEMNO]
WHERE ([t0].[ITEMNO] LIKE @p0) OR ([t0].[DESC] LIKE @p1)
-- @p0: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- @p1: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

我无法弄清楚如何在[rd]字段上获得Max函数......任何见解都会非常受欢迎。

2 个答案:

答案 0 :(得分:0)

您需要添加Group By。 这是一个应该有用的例子:

Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into MaxArrivalDate = Max(recDates.DTARRIVAL)
Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = MaxArrivalDate

答案 1 :(得分:0)

您的linq查询中还有一个Contains。如果这是正确的,这里是group by和max的完整linq查询:

Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into Group
Let MaxArrival = Group.Max(Function(p) p.recDates.DTARRIVAL)
Select [Item_ID] = ITEMNO, [Description] = DESC, [rd] = MaxArrival