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

StackOverflow https://stackoverflow.com/questions/23573383

Hello This is my first post here

I'm facing some issue with EF , I have tried the following code in VS 2010 with EF 5 and 6.

I have table called MYTABLE and field ReveivedTime which varchar(255) but this has Datetime values like "4/29/2014 12:00:00 AM". Note : I can not change the DataType and I can not write SP to Convert , I do have limitations, So I do have option to work with LAMBDA

I have tired the following code in LINQPad 4 itis working fine but the same is not working in VS2010 with EF 5/6.

getting error

LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.

Convert.ToDateTime(si.ReceivedTime) is causing the problem

   MYTable
  .Where (
      si => 
            ((Convert.ToDateTime(si.ReceivedTime) >= DateTime.Now.AddDays(-10)) && 
               (Convert.ToDateTime (si.ReceivedTime) <= DateTime.Now)
            )
   )
   .GroupBy (g => new 
                    {
                        Day = Convert.ToDateTime(g.ReceivedTime).Day,
                        Month = Convert.ToDateTime(g.ReceivedTime).Month,
                        Year = Convert.ToDateTime(g.ReceivedTime).Year,
                        City = g.City,
                    })
   .Select (
      g => 
         new  
         {
           Count = g.Count(),
           g.Key.Day,
           g.Key.Month,
           g.Key.Year,
           g.Key.City,
           Date = Convert.ToDateTime(g.Key.Year  + "/" + g.Key.Month + "/" + g.Key.Day),
         }
   )
   .OrderBy(x => x.Count)

Really appreciate your solution and advanced thanks too.

有帮助吗?

解决方案

Instead of Convert.ToDateTime (si.ReceivedTime) <= DateTime.Now try SqlFunctions.DateDiff("s", si.ReceivedTime, DateTime.Now) > 0

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top