0

Using entity framework, i am trying to select records and their related child records. The child records could be null, so i would just like to return an empty string if they are. I am getting a

null reference exception

when attempting to run the following code.

var query = ctx.UserAlerts.Include(x=>x.DocumentType).Where(x => x.UserId == userId).ToList();
var alerts = query.Select(u => new AlertConfigVM
            {
                UserId = u.UserId,
                Destination = u.AlertDestination,
                TypeofAlert = u.TypeofAlert,
                HourInterval = u.IntervalAsHours,
                DocumentTypeName= u.DocumentType.Name??string.Empty
            }).ToList();

here are my Entities

public class UserAlert
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public User User { get; set; }
    public int TypeofAlert { get; set; }
    public string AlertDestination { get; set; }
    public int? DocumentTypeId { get; set; }
    public virtual DocumentType DocumentType { get; set; }
    public int? IntervalAsHours { get; set; }
}

public class DocumentType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Key { get; set; }
}

and here is my return type.

public class AlertConfigVM
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public User User { get; set; }
    public int TypeofAlert { get; set; }
    public string Destination { get; set; }
    public int? DocumentTypeId { get; set; }
    public string DocumentTypeName { get; set; }
    public int? HourInterval { get; set; }
}
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Rick james
  • 824
  • 1
  • 11
  • 30

2 Answers2

3

Change this:

DocumentTypeName= u.DocumentType.Name??string.Empty

to this:

DocumentTypeName= u.DocumentType?.Name??string.Empty

This will allow the DocumentType to default to string.Empty if null.

tjcertified
  • 694
  • 7
  • 18
1

Since tjcertified's answer only works in Visual Studio 2015 and later, this solution should work regardless of environment:

var query = ctx.UserAlerts.Include(x=>x.DocumentType).Where(x => x.UserId == userId).ToList();
var alerts = query.Select(u => new AlertConfigVM
            {
                UserId = u.UserId,
                Destination = u.AlertDestination,
                TypeofAlert = u.TypeofAlert,
                HourInterval = u.IntervalAsHours,
                DocumentTypeName= u.DocumentType != null 
                                  ? u.DocumentType.Name != null 
                                      ? u.DocumentType.Name 
                                      : string.Empty 
                                  : string.Empty
            }).ToList();

The ?: operation is the ternary operator and is the same as a regular if-else statement.

Community
  • 1
  • 1
Cameron
  • 2,574
  • 22
  • 37