Liam
Liam

Reputation: 455

Entity Framework 4 Navigation property null value throws an exception

I am trying to setup editing functionality using MVC3 and entity framework 4. I have a navigation property adding to my customer entity to allow me to access a one to many related entity. I have the related entity defined as virtual - its the Customer property in the below CustomerSite entity

namespace CustomerOrders.Domain.Entities
{
public class CustomerSite
{
    [HiddenInput(DisplayValue = false)]
    [Key]
    public int CustomerSiteId { get; set; }
    [HiddenInput(DisplayValue = false)]
    [DisplayName("Customer Id")]
    public int CustomerId { get; set; }
    [Required(ErrorMessage = "Please enter a unit no/street name")]
    [DisplayName("Address Line 1")]
    public string AddressLine1 { get; set; }
    public virtual Customer Customer { get; set; }

}
}

When i try to save an edit to the CustomerSite entity i get the following exception

Object reference not set to an instance of an object.

Now when i inspect the model values, the only null value is the Customer navigation property so i assuming thats whats throwing the error? EF must automatically Populate the foreign key property as the customer id field is correctly populated when i inspect the model. Thats the field i was ecpecting to be a null as i havent done anyhting extra to insert the customer ID which i am not rendering an editor for in the view.

This is my save method

  public void SaveCustomerSite(CustomerSite customerSite)
    {
        if (customerSite.CustomerSiteId == 0)
        {
            context.CustomerSites.Add(customerSite);
        }
        context.SaveChanges();

        }

And this is how i have the relationship defined in the EF data context

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CustomerSite>()
            .HasRequired(x => x.Customer);
    }

Does anyone know if the navigation property being null at the time the edit is saved will be what is causing the excpetion and if so how can i resolve this?

All advice is appreciated.

EDIT================

This is the stack trace from the exception

at CustomerOrders.WebUI.Controllers.SiteAdminController.Edit(CustomerSite  customerSite) in C:\Users\administrator\documents\visual studio 2010\Projects \CustomerOrders\CustomerOrders.WebUI\Controllers\SiteAdminController.cs:line 43
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[]   parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext  controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15. <InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

Upvotes: 1

Views: 1272

Answers (2)

John M
John M

Reputation: 14668

An additional note.

In a master-detail setup (one-to-many) I had an issue where the detail portion was throwing an exception when only the master was being populated. In my controller I added a check on the master-detail for if it was null.

if(salesMain.SalesSub != null)
{
   //do something with SalesSub
}

Upvotes: 0

The Evil Greebo
The Evil Greebo

Reputation: 7138

 if (customerSite.CustomerSiteId == 0)

If customerSite is null when it's passed in, you cannot reference any properties.

Test for null before this line.

Upvotes: 2

Related Questions