views:

37

answers:

2

I have the following LINQ code:

docTypes = (from c in context.Citizenships join
            cdt in context.Citizenship_Document_Types 
                       on c.Country_Code equals cdt.Country_Code
            from cd in context.Citizenship_Documents
                              .Where(cd => cd.Citizenship_Id == c.Citizenship_ID)
                              .DefaultIfEmpty()
            where c.Citizenship_ID == citizenshipId
            select new CitizenshipDocument
    {
                Id = (int?)cd.Citizenship_Document_Id??-1,
                CitizenshipId = c.Citizenship_ID,
                DocumentTypeId = cdt.Citizenship_Document_Type_Id,
                DocumentTypeName = cdt.Citizenship_Document_Type_Name,
                DocumentCode = cd.Citizenship_Document_Code.ToArray(),
                ExpirationDate = cd.Expiration_Date,
                IssueDate = cd.Issue_Date
    }).ToList();

The issue is that when cd.Citizenship_Document_Code returns null I get an error when using .ToArray(). :

Object reference not set to an instance of an Object

How can I handle null values?

+1  A: 

You would handle nulls in a LINQ query the same as you would handle them anywhere else. Don't dereference a null value! For instance:

docTypes = (from c in context.Citizenships join
            cdt in context.Citizenship_Document_Types
            on c.Country_Code equals cdt.Country_Code
            from cd in context.Citizenship_Documents.Where(
                cd => cd.Citizenship_Id == c.Citizenship_ID).DefaultIfEmpty()
            where c.Citizenship_ID == citizenshipId
            select new CitizenshipDocument
            {
                Id = (int?)cd.Citizenship_Document_Id??-1,
                CitizenshipId = c.Citizenship_ID,
                DocumentTypeId = cdt.Citizenship_Document_Type_Id,
                DocumentTypeName = cdt.Citizenship_Document_Type_Name,
                DocumentCode = cd.Citizenship_Document_Code == null ?
                    null : 
                    cd.Citizenship_Document_Code.ToArray(),
                ExpirationDate = cd.Expiration_Date,
                IssueDate = cd.Issue_Date
            }).ToList();
John Saunders
Thanks. I thought I had tried this and had it fail. I must have had some other syntax error.
Jack Corbett
A: 

Consider handling the null with an appropriate null-object using something like the following extension method:

public static T ToNonNull<T>(this T input) where T : class, new()
{
  if (input != null)
  {
    return input;
  }
  return new T();
}

Usage would be something like:

DocumentCode = cd.Citizenship_Document_Code.ToNonNull().ToArray()

You could also have a specific ToNonNull() extension just for that type if you don't want a generic one.

Handcraftsman