I have several classes
public class Person
{
public int Id{get;set;}
public string Name{get;set;}
public virtual Institution Institution{get; set;}
}
public class Institution
{
public int Id{get;set;}
public string Name{get;set;}
public virtual InstitutionType InstitutionType { get; set; }
}
public class InstitutionType
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public virtual ICollection<Institution> Institutions { get; set; }
}
This class is a code first model that uses Entity Framework to pull records from tables in a DB. Often there are situations where there is no InstitutionType in the Institution table.
When I use the following code and there is no InstitutionType data for the record I get a Null Reference Exception.
cm.InstitutionTypeId = person.Institution.InstitutionType == null ? 0 : contact.Institution.InstitutionType.Id;
How should these situations be handled? Should my classes be redesigned?
(Edited to show lazy loading code sample)
Currently, there's no way around checking for a null reference before using a property of the possibly null object.
cm.InstitutionTypeId = (person.Insitituion != null && person.Institution.InstitutionType != null) ? contact.Institution.InstitutionType.Id : 0;
C# does not currently have a safe navigation operator, but according to this:
We'll probably be getting one soon: "?."
Alternatively, you can have your Institution property lazy load a new Institution instance, which has initializes with an InstitutionType whose ID is 0. Depending on the business logic you need when using these objects, this may or may not be the best approach. Since these are entity objects, you'll want to make sure you understand the data implications of creating new instances rather than possibly setting a reference to an existing default Institution or InstitutionType. Hope this helps.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
private Institution _Institution;
public Institution Institution
{
get { return _Institution ?? (_Institution = new Institution()); }
}
}
public class Institution
{
public int Id { get; set; }
public string Name { get; set; }
private InstitutionType _InstitutionType;
public InstitutionType InstitutionType
{
get { return _InstitutionType ?? (_InstitutionType = new InstitutionType() { Id = 0 }); }
}
}