2013-05-12 86 views
0

我运行一个ASP.NET MVC 3应用程序(C#)。EF 4不加载外键对象

我最近在我的数据库可为空的外键。这可能不是最佳实践,但对我的情况来说是必要的。所以,现在当我显示我的报告(ASPX视图引擎),为此,我在我的数据库将不会显示可为空的对象的值。

的数据结构现在(简化的)是如下:

Inventory 
________________ 
InventoryID int PK 
ShopID FK int NOT NULL 
ProductID FK int NULL 

对此的唯一的变化是产品ID曾经是不可为空。

我的ActionResult如下:

[HttpPost] 
public ActionResult InventoryReport(FormCollection formVariables, InventoryReportRequest reportRequest) 
     { 
      ModelContainer ctn = new ModelContainer(); 

      var query = ctn.Inventory.Where(ic => !ic.Deleted && ic.ShopID == reportRequest.ShopID); 

      if (reportRequest.ProductID.HasValue) 
      { 
       query = (from ic in query 
         where reportRequest.ProductID == ic.ProductID 
         select ic); 
      } 

      List<Inventory> checks = query.ToList(); 

      if (checks.Count > 0) 
      { 
       return View(checks); 
      } 
      else 
      { 
       return RedirectToAction("Index"); 
      } 
     } 

当调试虽然这动作,我可以看到,该产品ID被检索到,但是产品的对象保持为空。所以当我想在我的视图中显示我的结果时 -

<table class="normal" width="100%"> 
     <tr> 
      <th> 
       Date 
      </th> 
      <th> 
       Shop 
      </th> 
      <th> 
       **Product Name** 
      </th> 
      <th> 
       **Product ID** 
      </th> 
      <th> 
       Active 
      </th> 
     </tr> 

    <% foreach (var item in Model) { %> 
     <tr> 
      <td> 
       <%: Html.DisplayFor(modelItem => item.DateChecked) %> 
      </td> 
      <td> 
       <%: Html.DisplayFor(modelItem => item.Shop.Name) %> 
      </td> 
      <td> 
       **<%: Html.DisplayFor(modelItem => item.Product.Name) %>** 
      </td> 
      <td> 
       **<%: Html.DisplayFor(modelItem => item.Product.ProductID) %>** 
      </td> 
      <td> 
       <%: Html.DisplayFor(modelItem => item.Active) %> 
      </td> 
     </tr> 
    <% } %> 

    </table> 

带星号的项目显示为空白。

可以在任何提供意见,以什么我需要做什么来解决这个问题呢?如果需要了解更多信息,请只问:)

+0

试试这个'var query = ctn.Inventory..Include(“Shops”)。其中(ic =>!ic.Deleted && ic.ShopID == reportRequest.ShopID);'这会在查询中添加相应的更改到数据库。 – Saravanan 2013-05-12 14:25:03

+0

@saravanan感谢您的回复。我曾试图太没有结果:S – 109221793 2013-05-12 15:05:56

+0

作为格特·阿诺德指出,是否包含在上下文中的产品。您是否碰巧调试过代码并获取了相应关联中的值。 – Saravanan 2013-05-12 16:24:31

回答

2

其实,这是更令人惊讶的,如果你没有做任何更改查询Product以前加载。对于要加载Product你不得不使用Include,不论FK的是可为空或不

ctn.Inventory.Include("Product").Where(... 

反正现在添加Include,你会没事的。

+0

嗨,格特!谢谢回复。我已经修改了我的查询,但是我仍然没有任何运气。我以前从来不需要使用'包含',这很奇怪,尽管没有使用'包含'作为商店外键,所有商店属性仍然加载。 – 109221793 2013-05-13 08:25:31

+0

奇怪......我假设'ModelContainer'是一个上下文和'Inventory',只不过是一个DbSet(或ObjectSet)? – 2013-05-13 11:59:19