简体   繁体   中英

Why do I get specified cast is not valid while handling double?

Reading from a Microsoft SQL database where I have a column with just decimal value and no nulls I get the "specified cast is not valid" while trying to group the data. It's complaining on the "Tid" row.

(Using sql server 2008)

var resultat = (from row in ds.Tables[0].AsEnumerable()
                        let ansvarig = row.Field<string>("Ansvarig")
                        let namn = row.Field<string>("Namn")
                        let vecka = row.Field<int>("Vecka")
                        let tid = row.Field<double>("Tid")
                        group row by new { ansvarig, namn, vecka } into grp
                        select new
                        {
                            Ansvarig = grp.Key.ansvarig,
                            Namn = grp.Key.namn,
                            Vecka = grp.Key.vecka,
                            Total = grp.Sum(r => r.Field<double>("Tid"))
                        }).ToList();

If the type is decimal in SQL Server then it should map to System.Decimal in .Net, try:

row.Field<decimal>("Tid") //instead of double

If the column has no null value but it has Allow null set to true, then you need Nullable<decimal> or decimal?

See: SQL Server Data Type Mappings

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