The specified listing from the materialized type "System.DateTime" to the type "System.String" is not valid

I use 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 an error message:

The specified migration from the materialized type "System.DateTime" to the invalid type "System.String".

Any ideas why?

+6
source share
2 answers

It looks like you are putting a DateTime in a String variable in a linq request. I also assume that the first for the query is "results.Count ()", which actually executes the query and tries to populate any object that you populate. If you change the call to Count () to any method that will make the call (ToList (), First (), ...), you will see the same error.

When you project DateTime into a string, make sure you call ToString () with the format provider for the conversion.

+5
source

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

look at the entity class in this case T SRVM , you will find the IDate field of type string , which should be of type Datetime .

 public string IDate { get; set; } 

For

 public Datetime IDate { get; set; } 
+3
source

Source: https://habr.com/ru/post/969980/


All Articles