SO 上已经有一些关于 LINQ 枢轴的问题,虽然其中几个概述了我的确切问题,但我无法成功地将它们转化为可行的解决方案。 我觉得这主要是由于我的表中的连接所致。
如何将以下 SQL 存储过程脚本转换为 LINQ?
ALTER PROCEDURE [dbo].[GetTimesheetForWeekById]
@timesheetid int,
@begindate VarChar(20),
@enddate VarChar(20)
AS
BEGIN
SELECT T.TaskName,
SUM(
case DATEPART(weekday, TE.StartTime)
WHEN 1 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Sunday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 2 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Monday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 3 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Tuesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 4 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Wednesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 5 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Thursday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Friday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Saturday
FROM Tasks T
INNER JOIN TimeEntries TE on T.TaskID = TE.TaskID
WHERE TE.StartTime BETWEEN
(CONVERT(datetime, @begindate, 103)) AND (CONVERT(datetime, @enddate, 103))
AND TE.TimesheetID = @timesheetid
GROUP BY T.TaskName
END
好吧,假设外键有一个对象表示,类似于:
int timesheetId = ...
DateTime start = ..., end = ...
var qry = from timeEntry in ctx.TimeEntries
let date = timeEntry.StartTime.Date
where timeEntry.TimesheetId == timesheetId
&& date >= start
&& date <= end
group timeEntry by timeEntry.Task.TaskName into grp
select new {
TaskName = grp.Key,
Monday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Monday).Count(),
Tuesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Tuesday).Count(),
Wednesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Wednesday).Count(),
Thursday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Thursday).Count(),
Friday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Friday).Count()
};
不幸的是,一些细节取决于 SQL 提供程序 - 即哪些函数(如 DayOfWeek 等)它可以成功映射为 TSQL。如果您遇到问题请告诉我...
这个怎么样(修改Marc的):
var qry = from timeEntry in timeEntries
let date = timeEntry.StartTime.Date
where timeEntry.TimesheetId == timesheetId
&& date >= start
&& date <= end
group timeEntry by timeEntry.Task.TaskName into grp
select new
{
TaskName = grp.Key,
Monday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Monday)
.Sum(x=>x.EndTime.Subtract(x.StartTime).TotalMinutes),
Tuesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Tuesday)
.Sum(x => x.EndTime.Subtract(x.StartTime).TotalMinutes),
Wednesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Wednesday)
.Sum(x => x.EndTime.Subtract(x.StartTime).TotalMinutes),
Thursday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Thursday)
.Sum(x => x.EndTime.Subtract(x.StartTime).TotalMinutes),
Friday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Friday)
.Sum(x => x.EndTime.Subtract(x.StartTime).TotalMinutes),
};