Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query returns error "The expected type was 'System.Int32' but the actual value was null."

So this is the query:

from c in Contents
join cs in DepartmentSharings 
on c.ContentId equals cs.ContentId
select c.PrivateCategoryId.Value

When I run this I get:

A database operation failed while processing the request. InvalidOperationException: An exception occurred while reading a database value for property 'DepartmentSharing.ContentId'. The expected type was 'System.Int32' but the actual value was null.

Now I checked the DepartmentSharings.ContentId field in the database, its fk, int, not null. In the class it's public int ContentId { get; set; }. DepartmentSharing.ContentId cannot be null. Also, in LinqPad I can see it returns 58 rows before failing. Why am I getting this error?

like image 686
Shiran Dror Avatar asked Mar 02 '18 09:03

Shiran Dror


1 Answers

The only thing that will cause that error is if ContentId is a non-nullable int property, but somehow your database table is allowing NULL values for that column. Assuming EF is handling your database, that shouldn't happen, but it's possible you've changed something at some point and didn't migrate properly.

Regardless, you need to either change the property type to int? instead of int or alter the table to make the column NOT NULL and ensure all the rows have a non-NULL value.

like image 183
Chris Pratt Avatar answered Nov 03 '22 00:11

Chris Pratt