Linq – Null value cannot be assigned – LINQ query question

linq

I have the following LINQ query:

DataClassesDataContext dc = new DataClassesDataContext(); 
var query = from contact in dc.Contacts
            select new
            {
                ContactId = contact.ContactId,
                LastName = contact.LastName,
                FirstName = contact.FirstName,
                Addresses = contact.Addresses,
                Phones = contact.Phones,
                DOB = contact.BirthDate,
                LastNote = contact.Notes.Max(n => n.Created), //this line causes the error
                Status = contact.ContactStatus.ContactStatusName,
                EmailAddress = contact.Emails
            };

The line where I get the maximum created date for the notes collection causes the following exception to be thrown:

Exception: The null value cannot be assigned to a
member with type System.DateTime which
is a non-nullable value type.

How do I write the query to allow null values into the LastNote field? The DOB field is defined as DateTime? and has not problem handling nulls.

Best Answer

Think I figured it out.

If I cast the maximum note value to a nullable DateTime it seems to eliminate the exception. The following change worked for me:

LastNote = (Nullable<DateTime>)contact.Notes.Max(n => n.Created)

As others have pointed out, it can also be written using the shorthand notation for a nullable DateTime as follows:

LastNote = (DateTime?) contact.Notes.Max(n => n.Created)
Related Topic