Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidCastException in a LINQ query

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.

like image 533
venkat Avatar asked Jan 10 '12 13:01

venkat


People also ask

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

What is into in LINQ query?

Use into keyword in LINQ query to form a group or to continue a query after a select clause. In the above query, the 'into' keyword introduced a new range variable teenStudents, so the first range variable s goes out of scope.


2 Answers

select row.Field<int?>("Presently_Available")
like image 130
abatishchev Avatar answered Sep 27 '22 23:09

abatishchev


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

like image 41
Akrem Avatar answered Sep 28 '22 00:09

Akrem