开发者

handling null byte array values in a LINQ query

开发者 https://www.devze.com 2023-01-13 15:26 出处:网络
I have the following LINQ code: docTypes = (from c in context.Citizenships join cdt in context.Citizenship_Document_Types

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?


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号