views:

38

answers:

2

Lately I have run in a strange NullReferenceException. It pops up only occasionally why it is so hard to debug it for me. Today it happened again and I want to fix it now I have the error.

I have the following setup:

An asp.net view with relevant code:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WerkStageNu.Profiles>" %>
<%@ Import Namespace="WerkStageNu.Helpers" %>

<div class="listing"> 
    <div class="content"> 


        <h3><%=Html.ActionLink(Model.Persons.UserName, "Details", new { id = Model.ID } )%></h3>

And when running this it tells me that Model.Persons is null giving the following error, while the Model itself is loaded with the data from the (SQL) Database. I am using ADO.net entities. Retrieving the profile instead of using the model resulted in the same error.

<%=Html.ActionLink(WerkStageNu.Models.Repository.Instance.GetProfileByID(Model.ID)
.Persons.UserName, "Details", new { id = Model.ID } )%>

Did not do any good.

Some error images:

debug mode

stack trace

So far it seems a normal error, but when I checked my DB behind the request I found that this field is filled in and that the link is correct. SQL manager screens to show this information:

Profiles table:

profiles DB

Persons table:

persons DB

As one can see all the PersonIDs are set so normally all the links should be loaded? Sometimes this is the case, but sometimes however this nullreference pops up from out of nowhere. Am I forgetting something? Should I manually load something?

//edit

I notice

<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %> Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?

A: 

I notice

<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %>

Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?

bastijn
+2  A: 

It could be related to lazy loading the Persons collection.

Darin Dimitrov
Looks a lot like it, thanks for the link, didn't see that one.
bastijn