Mit Entity-Framework versuche ich, Datensätze und ihre zugehörigen untergeordneten Datensätze auszuwählen. Die untergeordneten Datensätze könnten null sein, daher möchte ich nur eine leere Zeichenfolge zurückgeben, wenn sie das sind. Ich bin eineLinq-Abfrage mit null untergeordneten Entitäten
null getting Ausnahme
beim Versuch, den folgenden Code auszuführen.
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();
hier sind meine 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; }
}
und hier mein Rückgabetyp ist. diese
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; }
}
Stellen Sie sicher, dass documentType nicht null ist, bevor Sie prüfen, ob dokumenttyp.name nicht null ist. – Forklift
wie würde ich das tun? Können Sie ein Beispiel veröffentlichen? –
Mögliches Duplikat von [Was ist eine NullReferenceException, und wie behebe ich sie?] (Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –