我正在尝试编写一个 LINQ-to-entities 查询,它将获取ICollection我的主要对象的导航属性,并将一些元数据附加到每个对象,这是通过将每个对象连接到另一个数据库表并使用聚合函数来确定的。所以主要对象是这样的:
public class Plan
{
...
public virtual ICollection<Room> Rooms { get; set; }
}
我的查询是这样的:
var roomData = (
from rm in plan.Rooms
join conf in context.Conferences on rm.Id equals conf.RoomId into cjConf
select new {
RoomId = rm.Id,
LastUsedDate = cjConf.Count() == 0 ? (DateTime?)null : cjConf.Max(conf => conf.EndTime)
}
).ToList();
我想要的是生成一些高效的 SQL,使用聚合函数MAX来计算LastUsedDate,如下所示:
SELECT
rm.Id, MAX(conf.EndTime) AS LastUsedDate
FROM
Room rm
LEFT OUTER JOIN
Conference conf ON rm.Id = conf.RoomId
WHERE
rm.Id IN ('a967c9ce-5608-40d0-a586-e3297135d847', '2dd6a82d-3e76-4441-9a40-133663343d2b', 'bb302bdb-6db6-4470-a24c-f1546d3e6191')
GROUP BY
rm.id
但是当我分析 SQL Server 时,它显示了来自 EF 的这个查询:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[RoomId] AS [RoomId],
[Extent1].[ProviderId] AS [ProviderId],
[Extent1].[StartTime] AS [StartTime],
[Extent1].[EndTime] AS [EndTime],
[Extent1].[Duration] AS [Duration],
[Extent1].[ParticipantCount] AS [ParticipantCount],
[Extent1].[Name] AS [Name],
[Extent1].[ServiceType] AS [ServiceType],
[Extent1].[Tag] AS [Tag],
[Extent1].[InstantMessageCount] AS [InstantMessageCount]
FROM [dbo].[Conference] AS [Extent1]
所以它从内存中选择所有内容Conference并Max()在内存中进行计算,这是非常低效的。如何让 EF 使用聚合函数生成正确的 SQL 查询?
慕田峪9158850
扬帆大鱼
相关分类