c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)' 方法

标签 c# entity-framework linq-to-entities

我正在尝试将一个应用程序转换为 EntityFrameWork codefirst。 我现在的代码是

 string sFrom  ="26/12/2013";
 select * FROM Trans where  CONVERT(datetime, Date, 105) >=   CONVERT(datetime,'" + sFrom + "',105) 

我试过了

 DateTime dtFrom = Convert.ToDateTime(sFrom );
TransRepository.Entities.Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

但是我遇到了这样的错误

LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method

请帮忙 提前致谢

最佳答案

当你这样做时:

TransRepository.Entities.Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

LINQ to Entities 无法将大多数 .NET Date 方法(包括您使用的转换)转换为 SQL,因为没有等效的 SQL。 您需要做的是执行以下操作:

 DateTime dtFrom = Convert.ToDateTime(sFrom );
  TransRepository
 .Entities.ToList()//forces execution
 .Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

但等待上面的查询将获取整个数据,并对其执行.Where,你肯定不希望这样,

简单的灵魂是this , 就个人而言,我会将我的实体字段设置为 DateTime 并将 db 列设置为 DateTime

但是,由于您的 db/Entity Date 字段是字符串,您没有任何其他选择,只能将实体和 db 中的字段更改为 DateTime 然后做比较

关于c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20797158/

相关文章:

c# - 数据保护 key 未保留到 Azure

c# - 指定类本身的泛型类的基类约束

c# - Linq 表达式嵌套属性,与字符串比较

c# - 删除不带 .Include 的选择 N+1

entity-framework-4 - 如何将 Entity Framework 中的 DbSet 转换为 ObjectQuery

sql - 为什么 LINQ to Entities 为我创建子查询?

c# - 减少 WMI 查询执行时间

.net - 枚举作为 Entity Framework 5 中的键在多对多连接上抛出错误

entity-framework - 我可以一次性忽略 Automapper 属性吗?

.net - 将 Npgsql 用于 EntityFramework 的 Postgis 地理类型