InvalidCastException in a LINQ query
Asked Answered
P

3

13

For this LINQ query I'm getting the exception below:

(from row in ds.Tables[0].AsEnumerable()
 where row.Field<string>("Dept_line_code") == DeptCode &&
 row.Field<string>("Skill_Name") == skill &&
 row.Field<string>("Acct_Code") == account && row.Field<string>("Location") == dtNewTable.Rows[intRow]["Location"].ToString()
 select row.Field<int>("Presently_Available") == null ? 0 : row.Field<int>("Presently_Available")
).FirstOrDefault();

Exception information:

Exception type: InvalidCastException

Exception message: Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type.

I don't know nullable type and I'm not getting how to use nullable type to overcome this exception.

Priscilapriscilla answered 10/1, 2012 at 13:26 Comment(4)
Briefly: by default, primitive types (such as int, double, float, ...) can't be assigned null values. The solution to this problem is to use a nullable type instead (like int?), which is really just a wrapper around the primitive type.Selvage
Seems that you use DataSet, probably filled by DataAdapter. Then you can fill not a DataSet but a DataTable, if you're sure that resulting query contains only the single table.Cohlette
When we need to use nullable types? what scenarios? why we have to use the same? Need information about the purpose and Pros or Cons with NUllable types?Priscilapriscilla
@sukumar Google "nullable types C#" and read about it. You need to learn how to research your own issues rather than asking people to give you answers.Selvage
B
25

you have to make int accept null value => int?

row.Field<int?>("Presently_Available") == null ? 0 : row.Field<int>("Presently_Available") ;

and this is a link for the Nullable Types

Blatant answered 10/1, 2012 at 13:28 Comment(2)
You should probably give a link or a brief explanation of nullable types in your answer. The OP isn't going to understand why int? fixes his problem.Selvage
Wow, a couple hours of searching to find out I just needed a question mark!Didactic
C
9
select row.Field<int?>("Presently_Available")
Cohlette answered 10/1, 2012 at 13:28 Comment(0)
T
7

change row.Field<int> to row.Field<int?>

Thirtyone answered 10/1, 2012 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.