So I have a city model. Each city has a Name attribute as well as others and a StateId and a State (StateId is a foreign key). State also has a Name property. I wanted to create a property called “Name_Full” that was Name + “, ” + State.Name, so like “Ashland, OR”. However, I get the error “Object reference not set to an instance of an object” whenever I want to reference the property, however.
Here is the code of the city model:
public class City
{
public int CityId { get; set; }
[Required]
public string Name { get; set; }
public int StateId { get; set; }
public State State { get; set; }
public List<Store> Stores { get; set; }
public string Name_Full
{
get
{
return Name + ", " + State.Name;
}
}
}
(I didn’t include the namespace and using stuff).
Presumably some of the State tables are null in your database; so when you try to pull the Name property of a null object, the exception gets thrown. Handle the null case using something like this: