Skip to main content
 首页 » 编程设计

c#之如何解决 'Only Parameterless constructors and initializers...' 错误

2024年02月06日11www_RR

我正在尝试编写一个 LINQ 查询,该查询返回“DateDue”字段距当前日期不到 8 天的行。 DateDue 字段可以为空。这是我的查询:

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 对象有关,但我不知道如何解决它。

非常感谢任何帮助/指导。

请您参考如下方法:

完全不使用 let 子句,您可能需要考虑使用 DateDiff SqlFunctions 类的函数,它是专门为执行更复杂的 LINQ to Entities 查询而构建的。也就是说,您可能希望在 where 子句中执行以下操作:

where SqlFunctions.DateDiff("DAY", DateTime.Now, uc.DateDue) < 8 

在我看来,此函数最好的部分是 DateTime 参数都可以为 null,因此您甚至不需要先进行 null 检查。