我正在将我的项目转换为使用EF,并且还希望将存储过程转换为Linq-to-entities查询。
我的SQL查询(简单版本),我无法转换:
SELECT
CategoryID, Title as CategoryTitle,Description,
LastProductTitle,LastProductAddedDate
FROM
(
SELECT
C.CategoryID, C.Title,C.Description, C.Section,
P.Title as LastProductTitle, P.AddedDate as LastProductAddedDate,
ROW_NUMBER() OVER (PARTITION BY P.CategoryID ORDER BY P.AddedDate DESC) AS Num
FROM
Categories C
LEFT JOIN Products P ON P.CategoryID = C.CategoryID
) OuterSelect
WHERE
OuterSelect.Num = 1
单词:我想返回所有类别(来自Categories表)以及最后添加到此类别的产品(从Products表)添加的标题和日期。
如何使用实体框架工作查询实现此目的? 以最有效的方式。
答案 0 :(得分:-1)
在这种情况下是否需要Row_Number()?
以下内容返回Northwind数据库中所有客户的最新订单:
from c in Customers
join o in Orders on c.CustomerID equals o.CustomerID
group o by new { c.CustomerID, c.ContactName} into g
select new {
CustomerID = g.Key.CustomerID,
Name = g.Key.ContactName,
OrderDate = g.Max(a=> a.OrderDate)
}
创建的查询(来自LinqPad)是
SELECT MAX([t1].[OrderDate]) AS [OrderDate], [t0].[CustomerID], [t0].[ContactName] AS [Name]
FROM [Customers] AS [t0]
INNER JOIN [Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]
GROUP BY [t0].[CustomerID], [t0].[ContactName]
这个改为左连接
from c in Customers
join o in Orders on c.CustomerID equals o.CustomerID into g
from a in g.DefaultIfEmpty()
group a by new { c.CustomerID, c.ContactName} into g
select new
{
g.Key.CustomerID,
g.Key.ContactName,
RecentOrder = g.Max(a=> a.OrderDate)
}
,生成的查询是
SELECT MAX([t1].[OrderDate]) AS [RecentOrder], [t0].[CustomerID], [t0].[ContactName]
FROM [Customers] AS [t0]
LEFT OUTER JOIN [Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]
GROUP BY [t0].[CustomerID], [t0].[ContactName]