2013-05-12 33 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