【问题标题】:How can I remove the time part from a nullable datetime in where condition of Linq如何在 Linq 的 where 条件下从可为空的日期时间中删除时间部分
【发布时间】:2021-09-17 03:40:47
【问题描述】:

我现有的 Linq 语句无法在 where 条件中应用可为空的日期时间模型值。当我使用 shortdatestring() 应用日期时间时,会显示以下错误:

.Where(ti => ti.Outer.EmpCode == __empcode_0 && ti.Outer.ClockDateFormatted == __ToShortDateString_1)' 无法翻译。以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估

这是代码

考勤模式

public string Code { get; set; }
public DateTime? ClockedDate { get; set; }

public ICollection<Attendance> GetClockList(string code, DateTime datefrom)
{
    ICollection<Attendance> data = new List<Attendance>();
    data = (from log in ctx.Attendance
            join emp in ctx.Employee on log.EmpCode equals emp.EmployeeID.ToString()
            where log.EmpCode == empcode
            && log.ClockedDate.Value.ToShortDateString() == datefrom.ToShortDateString() // Here I have to give the ClockedDate without time 
            select new Attendance 
            {
              
                EmployeeName = emp.EmployeeName,
                ClockedDate = log.ClockedDate,

            }
            ).ToList();

    return data;
}

但在 where 条件下使用shortdateString() 给出日期时间时会显示错误

【问题讨论】:

标签: c# entity-framework linq .net-core entity-framework-core


【解决方案1】:

如果你使用 ms sql 你可以试试这个

.....

  where log.EmpCode == empcode
         && EF.Functions.DateDiffDay(log.ClockedDate, datefrom)==0

【讨论】:

    【解决方案2】:

    你可以试试

     && log.ClockedDate?.Date == datefrom.Date
    

    但如果这不起作用,您可能需要EF Functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 2012-12-26
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2019-07-05
      相关资源
      最近更新 更多