arithehun
arithehun

Reputation: 25

ASP.NET MVC Model with a foreign key property

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).

Upvotes: 1

Views: 4049

Answers (2)

skub
skub

Reputation: 2306

Make sure that when you call Name_Full, the State object must be loaded and not null. You can link the foreign key explicitly if you are concerned that the forein key relationship is not there:

// Foreign key to state
[ForeignKey("State")] 
public int StateId { get; set; } 
public virtual State State { get; set; } 

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102753

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:

return Name + ((State == null) ? "" : ", " + State.Name);

Upvotes: 1

Related Questions