Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The specified cast from a materialized 'System.DateTime' type to the 'System.String' type is not valid

I'm using Entity Framework 5 and when count() is called from below

string sqlStr = @"SELECT top 20 ID, 
               CAST(DOI as DATETIME) as IDate
               FROM DTable";

var results = db.Database.SqlQuery<SRVM>(sqlStr);


//get total count
var total = results.Count();

I get the error:

The specified cast from a materialized 'System.DateTime' type to the 'System.String' type is not valid.

Any ideas why?

like image 507
piris Avatar asked May 28 '14 14:05

piris


1 Answers

It looks like you are placing a DateTime into a String variable in a linq query. I'm also guessing that the first to the query is the "results.Count()" which is actually executing the query and trying to populate whatever object you are populating. If you change the Count() call to any method that will execute the call (ToList(), First(), ...) you will see the same error.

When you are projecting a DateTime into a string match sure you are calling ToString() with a format provider to make the conversion.

like image 175
Fran Avatar answered Oct 02 '22 00:10

Fran