Accepted answer

I'm guessing the issue is right here:

ReleaseYear = (int) shows.ReleaseYear

Why do you have to cast shows.ReleaseYear to an int? Is it because it's not already an int? Maybe it's actually a Nullable<int>?

An int can't hold a null value, and the error is telling you that it's encountered a null value in the data, so that value can't be cast to an int.

You'll either need to change your data to not allow null values for that field, or change your type to a Nullable<int> (or int? for short).


It tells you right in there:

The cast to value type 'Int32' failed because the materialized value is null.

This is the offending line:

ReleaseYear = (int) shows.ReleaseYear,

Check your data and make sure everything has a ReleaseYear, or switch to using int?.


If you are getting null values then try using these methods for casting -

Convert.ToInt32(string), This would return 0 if value used for parsing is null.

Int32.TryParse(string, out int), this would return true / false when it could parse / not respectively.

In your program before consuming the parsed value, check whether it is valid or not.

Related Articles