我正在尝试编写一个LINQ查询,该查询返回" DateDue"字段距离当前日期不到8天。 DateDue字段可以为null。这是我的疑问:
var employees = (from u in Session.Context.Users
join cu in Session.Context.CompanyUsers
on u.UserId equals cu.UserId
join c in Session.Context.Companies
on cu.CompanyId equals c.CompanyId
join uc in Session.Context.UserCourses
on cu.CompanyUserId equals uc.CompanyUserId
join crs in Session.Context.Courses
on uc.CourseId equals crs.CourseId
join so in Session.Context.ServicesOffereds
on crs.ServicesOfferedId equals so.ServicesOfferedId
join jt in Session.Context.JobTitles
on u.JobTitleId equals jt.JobTitleId
let DaysBeforeExpiring = (new DateTime(
DateTime.Now.Year,
uc.DateDue.HasValue ? uc.DateDue.Value.Month : DateTime.Now.Month,
uc.DateDue.HasValue ? uc.DateDue.Value.Day : DateTime.Now.Day) - DateTime.Now).TotalDays
where DaysBeforeExpiring < 8
where c.ParentId == companyId || c.CompanyId == companyId
where cu.IsActive
where uc.Passed == false &&
uc.DateDue > DateTime.Now &&
uc.DateCompleted == null
select new NonCompliantEmployeesModel()
{
UserId = u.UserId,
UserCourseId = uc.UserCourseId,
JobTitle = jt.JobTitle1,
CompanyId = cu.CompanyId,
CompanyName = c.CompanyName,
FirstName = u.FirstName,
LastName = u.LastName,
State = u.State,
EmailAddress = u.EmailAddress,
IsActive = cu.IsActive,
ServiceOffered = so.ServiceName,
DueDate = uc.DateDue,
Days = DaysBeforeExpiring
});
但是当我运行项目时,我收到Only parameterless constructors and initializers are supported in LINQ to Entities.
错误消息。我认为这与我在查询中创建新DateTime
对象的事实有关,但我不知道如何绕过它。
非常感谢任何帮助/指导。
答案 0 :(得分:4)
根本不考虑使用let
子句,您可能需要考虑使用SqlFunctions
类的DateDiff函数,该函数专门用于执行更复杂的LINQ to Entities查询。也就是说,您希望在where
子句中执行以下操作:
where SqlFunctions.DateDiff("DAY", DateTime.Now, uc.DateDue) < 8
在我看来,这个函数最好的部分是DateTime
参数都可以为空,所以你甚至不需要先打扰进行空检查。