0

I am using ASP.NET MVC 3 and Entity Framework 4.1 code first.

I have the following defined in my database context class:

public class HefContext : DbContext
{
   public DbSet<GrantApplication> GrantApplications { get; set; }
   public DbSet<MaritalStatusType> MaritalStatusTypes { get; set; }
}

My MaritalStatusType class:

public class MaritalStatusType : IEntity
{
   public int Id { get; set; }
   public string Name { get; set; }
   public bool IsActive { get; set; }
}

In my view model I have the following:

public class GrantApplicationDetailsViewModel
{
   public int MaritalStatusTypeId { get; set; }
   public MaritalStatusType MaritalStatusType { get; set; }
}

View code to display the marital status type name:

<tr>
   <td><label>Marital Status:</label></td>
   <td>@Model.MaritalStatusType.Name</td>
</tr>

In my controller's action method I get the grant application object by id. It has a marital status type id from the grant application table. I then map the grant application object to my GrantApplicationDetailsViewModel. That's fine. But when I want to specify the name of the marital status type in my view then it gives me errors, object not set to an instance of an object. How would I get this to work?

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234
  • 1
    You need to make sure your navigation property in GrantApplication is annotated properly and is loaded during query http://stackoverflow.com/questions/6144163/entity-framework-4-1-code-first-navigation-property-not-loading-when-only-the-id – Muhammad Hasan Khan Sep 14 '11 at 10:38

1 Answers1

0

I just added the virtual property in my grant application object and now it seems to work just fine.

public class GrantApplication : IEntity
{
   public int Id { get; set; }

   public int MaritalStatusTypeId { get; set; }
   public virtual MaritalStatusType MaritalStatusType { get; set; }
}
Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234
  • Yeah from what ive heard its recommanded to put all your variables virtual. This is intended for EF. – Rushino Sep 14 '11 at 13:07