views:

85

answers:

1

I'm trying to understand why, sometimes, my sub-objects disappear.

In my List view, I have the standard

<% foreach (var item in Model)

and when I inspect the item and the model, I can see that item.Map has a couple of elements.

In fact, in my List view I can do:

  <% foreach (var map in item.Map)
  <% Html.RenderPartial("MapView", map); %>

and MapView can access and display all the properties. I'm including the sub-objects with:

  list = from item in _entities.DataTable
           .Include("LookupTable1")
           .Include("Map")
           .Include("Map.LookupTable2") select item;
  return View("List", list);

But if I try to do:

 <%= Html.Encode(item.Map.FirstOrDefault().Field)%>

I get a null pointer exception, and item.Map has 0 elements.

Can anyone explain why this is happening?

A: 

You could probably do without the .Include statements. I'm not sure if that solves your problem though, without knowing the cause of the null-pointer.

Just as a note: when doing MVC, you probably shouldn't be doing Linq queries in the view (like .FirstOrDefault).

list = from item in _entities.DataTable
       select new
       {
           Name = item.Name
           Maps = item.Maps
       };

Using this syntax you can execute more Linq queries in the controller instead

list = from item in _entities.DataTable
       select new
       {
           Name = item.Name
           FirstMap = item.Maps.FirstOrDefault()
       };

Or even

list = from item in _entities.DataTable
       select new
       {
           Name = item.Name
           Maps = from map in item.Maps
                  where map = somecondition
                  select map
       };
Sander Rijken