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

asp.net c# entity-framework

Question

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?

1
6
9/9/2015 6:29:51 AM

Accepted Answer

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.

5
5/28/2014 2:33:36 PM

Popular Answer

When you use Database.SqlQuery<T> the exception targetsite is on : T GetValue(System.Data.Common.DbDataReader, DateTime)

review your entity class on this case T is SRVM you will find IDate field of type string which should be of type Datetime.

public string IDate { get; set; }

To

public Datetime IDate { get; set; }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow