简体   繁体   中英

System.InvalidCastException: Specified cast is not valid (linq query)

Specified cast is not valid error at line: select new File.Models.FileDetail(). DTTT in the code is a datatable, FileDetial is a class in a Model which has Filename,Dt,receivedcount,status params. I have checked all the Field datatypes and they are correct. Not sure why I'm getting this error.

return (from row in DTTT.AsEnumerable()
                        select new File.Models.FileDetail()
                         {
                             Filename = row.Field<string>("name"),
                             Dt = row.Field<DateTime?>("Dt"),
                             ReceivedCount = row.Field<int?>("count"),
                             status = row.Field<string>("status")

                         }

                    ).ToList();

You should be able to cast it as a TimeSpan :

 Dt = row.Field<TimeSpan>("Dt");

OR

Dt = (DateTime)(row.Field<DateTime>("Dt") == DBNull.Value ? DateTime.MinValue :row.Field<DateTime>("Dt"));

Dbtype of my "DT" field is char and the ReceivedCount property field is declared as Datetime in my model. So there was a invalid cast exception. changing my model field datatype to string worked. Thanks everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM