【问题标题】:LINQ to Entities does not recognize the method 'System.String ToString(System.String)'LINQ to Entities 无法识别方法“System.String ToString(System.String)”
【发布时间】:2018-04-06 15:00:31
【问题描述】:

我试图在获取记录时比较存储在 sql 中的月份日期,但它抛出了异常。

public partial class LateRequest
{
    public int LateRequestID { get; set; }
    public Nullable<int> EmpID { get; set; }
    public Nullable<int> TeamLeadAppr { get; set; }
    public Nullable<int> DeptLeadAppr { get; set; }
    public Nullable<System.DateTime> lateDate { get; set; }
}

在我的计算课中我有;

public int getMonthlyLatesApproved(int empId)
{
    DateTime today = DateTime.Now;
    var getMonth = today.Month
    var lateApproved = (from obj in db.LateRequests
                        where obj.EmpID == empId
                        && obj.TeamLeadAppr == 1 && obj.DeptLeadAppr == 1
                        && obj.lateDate.Value.ToString("mm") == getMonth.ToString()
                        select obj).Count();
    return lateApproved;
}

这不起作用,所以我尝试使用 LINQ,例如:

return db.LateRequests.Where(x => x.EmpID == empId && x.TeamLeadAppr == 1 && x.DeptLeadAppr == 1 &&
                                  x.lateDate.Value.ToString("mm") == getMonth.ToString()).Count();

这失败了,我读了here 并尝试了AsEnumerable()

如下所示;

 return db.LateRequests.Where(x => x.EmpID == empId && x.TeamLeadAppr == 1 && x.DeptLeadAppr == 1 &&
                                  x.lateDate.Value.ToString("mm") == getMonth.ToString()).AsEnumerable().Count();

`LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method.when i try to format my date

我需要了解如何在检索记录时将 c-sharp 与 sql 命令混合使用?

【问题讨论】:

  • 日期时间的mm 格式返回分钟,而不是月份

标签: c# linq


【解决方案1】:

您需要的是SqlFunctions.DatePart 方法。

&& SqlFunctions.DatePart("month", obj.lateDate) == getMonth

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2013-07-13
    相关资源
    最近更新 更多