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; }
}