asp.net mvc select 在 Linq to entity 中带有日期

asp.net mvc select with date in Linq to entity

当select这是我的代码时,我在 Linq to entity 中遇到问题
我想 select 带日期和 ID

    Login Lo = new Login();
    DateTime CurrentDate = DateTime.Now;         
    Lo = db.Logins.Where(i => i.Emp_id == employee.id &&
     DbFunctions.TruncateTime(i.WorkDay).Value.Date == DbFunctions.TruncateTime(CurrentDate).Value).FirstOrDefault();

它给我这个错误:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

要解决您的问题,您可以这样做:

DateTime CurrentDate = DateTime.Now.Date;   
var result= db.Logins.Where(i => i.Emp_id == employee.id &&
                                 DbFunctions.TruncateTime(i.WorkDay) == currentDate).FirstOrDefault();

您的问题是因为 Linq to Entities 提供程序无法将 Date 属性 中定义的操作转换为 SQL 中的正确表达式:

    // Returns the date part of this DateTime. The resulting value
    // corresponds to this DateTime with the time-of-day part set to
    // zero (midnight).
    //
    public DateTime Date {
        get { 
            Int64 ticks = InternalTicks;
            return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind);
        }
    }

这就是为什么我的建议是,在您的查询之外,从 DateTime.Now 调用 Date 属性,这样您将获得不带时间部分的当前日期,并且在您的查询,不需要调用Date属性,那是DbFunctions.TruncateTime方法

的作用