【问题标题】:LINQ to Entities does not recognize the method ToDateTime(System.String)LINQ to Entities 无法识别方法 ToDateTime(System.String)
【发布时间】:2016-03-29 09:31:06
【问题描述】:

我必须使用“转换为日期时间”的方法来将日期时间与参考月份和年份进行比较,如下所示

var res =  db.Table1
//other tables, and where conditions
.Select(x => new MyObj
{
      //...
      Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(Convert.ToDateTime("01/" + x.month + "/" + x.year), 1))).Description
})

我知道 Convert.ToDateTime 不能从提供者那里翻译成 sql,我需要一个想法来做那个查询。

更新:我不会在转换之前实现查询,因为这显然意味着获取所有记录。

【问题讨论】:

标签: c# entity-framework linq datetime


【解决方案1】:

我想我找到了方法

var res =  db.Table1
//other tables, and where conditions
.Select(x => new MyObj
{
      //...
      Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(System.Data.Entity.DbFunctions.CreateDateTime(x.year, x.month, 1, 0, 0, 0), 1)).Description
})

【讨论】:

    【解决方案2】:

    这有点粗略,但您可以在解析日期之前具体化 SQL 查询以列出:

    var res = db.Table1.ToList()
    //other tables, and where conditions
    .Select(x => new MyObj
    {
    //...
        Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(DateTime.Parse("01/" + x.month + "/" + x.year))).Description
    })
    

    【讨论】:

    • 如果可能的话,我之前不会实现查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多