Today I ran into a problem when running the following Linq query with an “outer join”.
from au in dcApp.aspnet_Users where au.UserId == new Guid("X") select new { au.UserName, au.ApplicantInfo.FirstName, au.ApplicantInfo.LastName, au.ApplicantInfo.CurrentStep };
The problem is that the Current Step is a not null column in the database; so it is of type int not int? . But in this query, I’m using Linq to get the ApplicantInfo row associated with the aspnet_Users row. The ApplicantInfo row might or might not exist. When the row does not exist linq is trying to convert that null into an int type so you get the following error:
“The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.”
What is really interesting is that it is only throwing that error with the CurrentStep column in the ApplicantInfo table, not with the FirstName or LastName cols that are also not null in the db. This probably has to do with the fact that the string type is a reference type (and the int type is a value type) and C# treats strings in unique ways.
This is the work-around I came up with:
from au in dcApp.aspnet_Users where au.UserId == new Guid("X") select new { au.UserName, au.ApplicantInfo.FirstName, au.ApplicantInfo.LastName, CurrentStep = au.ApplicantInfo == null ? "" : au.ApplicantInfo.CurrentStep.ToString() };