... But it's not null.
FYI - Many threads exist on this error, but none that I've seen using an anonymous type.
I'm Getting an odd InvalidOperationException in a Linq query.
message: "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."
The confusing thing is that it's erroring when creating an anonymous type:
var workstepid = 484,449;
var wsData = ion.xWorkSteps
.Where(w => w.WorkStepId == workstepId)
.Select(w => new
{
w.WorkStepId,
w.ServiceId,
w.Service.TitleId,
w.Service.Title.OrderId,
w.Service.Title.AltTitleId
}).SingleOrDefault();
In LinqPad this particular query runs just fine and the workstepId used returns an integer value for each property of the anonymous type. So why a casting error when there is no null value for any property!?
FYI, the last property AltTitleId is a nullable int, and the other properties are ints. Also, this code was written weeks ago and I didn't get this error until today. Is something funky w/ my EF?
Edit: SOLVED
We use soft-delete in our db's, setting deleted records to Acive=0. It turns out that there is a property set in EF on the edmx tables filtering out inactive records (filter for Active=1). Naturally, this wouldn't effect Linqpad which gives me the expected result, but since this was an older record I was testing, the title record (Service.Title) had been marked Active=0 and was therefore returning null.
Thanks to everyone for the help.