tags:

views:

2224

answers:

5

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.

+7  A: 

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)
joshb
I was just about to suggest that
Jeremy
That will work, though just FYI the shorthand of DateTime? is equivalent to Nullable<DateTime> (see Keltex's post)
Adam Robinson
+9  A: 

Rewrite that line as:

LastNote = (DateTime?) contact.Notes.Max(n => n.Created),
Keltex
+1  A: 

You could do that, or you could alter your database schema so that the column 'Created' does not allow nulls.

The scenario is arising because one of the rows comes back with a null value for Created. If the db didn't allow nulls, the scenario would never occur.

You'd still get a null back from the call to Max if the contact didn't ever create any notes.
Matt Hamilton
+1  A: 

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

Couldn't find this on the net so i hope this helps others.

ChrisKolenko
A: 

In VB is something like:

LastNote = CType(contact.Notes.Max(n => n.Created), Global.System.Nullable(Of Date))

I think...

Txugo