Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null value cannot be assigned - LINQ query question

Tags:

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.

like image 392
joshb Avatar asked Apr 22 '09 02:04

joshb


2 Answers

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)
like image 140
joshb Avatar answered Oct 22 '22 22:10

joshb


Rewrite that line as:

LastNote = (DateTime?) contact.Notes.Max(n => n.Created),
like image 34
Keltex Avatar answered Oct 22 '22 23:10

Keltex