简体   繁体   中英

Specified cast is not valid in linq query

Is there some way rather than try and error to specify which field makes the problem and what's the correct field type ?

I get the following exception :

Specified cast is not valid.

 var vacStatiscs = from x in dtGivenBal.AsEnumerable()
                                  join y in dtTakenBal.AsEnumerable()
                                  on x["emp_num"].ToString() equals y["emp_num"].ToString()
                                  into joined
                                  from j in joined.DefaultIfEmpty()
                                  select new
                                  {
                                      emp_num = x.Field<int>("emp_num"),
                                      name = x.Field<string>("name"),
                                      startBal = x.Field<int>("startBal"),
                                      prevMon = x.Field<int>("PrevMon"),
                                      added = x.Field<int>("Added"),
                                      taken = (j == null) ? 0 : j.Field<Int32>("sum")

                                  };

Now if I remove startBal ,prevMon ,added , I get no exceptions.

Note: the previous fields are result of COUNT and SUM SQL queries

There's no direct way to detect which field makes the problem.

To answer your second question how to find out the correct field types:

Type fieldType = dtGivenBal.Columns["startBal"].DataType;

So you can use the DataTable.Columns collection to determine the type of each column(fe via debugger). On this way you will also find out the wrong types.

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