开发者

LINQ to Entites: sub-objects disappearing

开发者 https://www.devze.com 2022-12-14 08:59 出处:网络
I\'m trying to understand why, sometimes, my sub-objects disappear. In my List view, I have the standard

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(开发者_StackOverflow"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?


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
       };
0

精彩评论

暂无评论...
验证码 换一张
取 消