Anyname Donotcare
Anyname Donotcare

Reputation: 11423

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

Upvotes: 4

Views: 13865

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

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(f.e. via debugger). On this way you will also find out the wrong types.

Upvotes: 6

Related Questions