Neal Helman
Neal Helman

Reputation: 75

MVC3 Razor EF can't test in a strongly typed view for the existence of an object

I have a strongly typed MVC3 Razor view in which I want to display one actionlink or another, depending on whether or not a child object exists in the model. I am unable to tell how to test for the object's existence, something I thought would be pretty straightforward. I'm using Entity Framework 4.1 to generate the underlying relationships, database, and entities.

My POCO classes (much abbreviated):

public class Pet
{
    public int PetID { get; set; }

    public virtual InsurancePolicy InsurancePolicy { get; set; }
}

public class InsurancePolicy
{
    [ForeignKey(Pet)]
    public int InsurancePolicyID { get; set; }

    public virtual Pet Pet { get; set; }
}

In the view, I thought I wanted to evaluate something like:

@foreach(var item in Model) 
{
    @if(string.IsNullOrEmpty(item.InsurancePolicy.InsuranceID.ToString()))
    {
        @Html.ActionLink("action link to create new InsurancePolicy")
    }
    else
    {
        @Html.ActionLink("action link to edit existing InsurancePolicy")
    }
}

Of course, if the Pet object has no associated InsurancePolicy yet, the conditional fails: Object reference not set to an instance of an object. I've been unable to find the equivalent of IsObject or any way to evaluate the nonexistence of the object without raising this error.

Can anyone point me to a way to make this work?

Upvotes: 0

Views: 163

Answers (1)

SLaks
SLaks

Reputation: 887837

You're looking for

if (item.InsurancePolicy == null)

Upvotes: 3

Related Questions