Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to convert one application to EntityFrameWork codefirst. My present code is

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

And i tried

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

But I got an error like this

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

Please help Thanks in advance

like image 472
pravprab Avatar asked Dec 27 '13 08:12

pravprab


People also ask

What is LINQ query in SQL Server?

LINQ to SQL is a component of . NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. Relational data appears as a collection of two-dimensional tables (relations or flat files), where common columns relate tables to each other.

What are the factors to be noted while handling LINQ to SQL queries?

LINQ to SQL needs a Data Context object. The Data Context object is the bridge between LINQ and the database. LINQ to Objects doesn't need any intermediate LINQ provider or API. LINQ to SQL returns data of type IQueryable<T> while LINQ to Objects returns data of type IEnumerable<T> .


2 Answers

when you do this:

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

LINQ to Entities cannot translate most .NET Date methods (including the casting you used) into SQL since there is no equivalent SQL. What you need to do is to do below:

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

but wait the above query will fetch entire data, and perform .Where on it, definitely you don't want that,

simple soultion would be this, personally, I would have made my Entity field as DateTime and db column as DateTime

but since, your db/Entity Date field is string, you don't have any other option, other than to change your field in the entity and db to DateTime and then do the comparison

like image 62
Manish Mishra Avatar answered Oct 26 '22 23:10

Manish Mishra


Why is your date column a string? Shouldn't it be a DateTime?

Regardless, if you attempt to perform conversions using .NET functions in a .Where statement against a repository of entities, you'll get that error.

Your best option would be to change that column from a string to a DateTime and proceed from there. If you do, the .Where statement would be:

DateTime dtFrom = Convert.ToDateTime(sFrom );
var something = TransRepository.Entities.Where(x  => x.Date >= dtFrom) ;
like image 21
Ann L. Avatar answered Oct 27 '22 01:10

Ann L.