我運行一個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>
帶星號的項目顯示爲空白。
可以在任何提供意見,以什麼我需要做什麼來解決這個問題呢?如果需要了解更多信息,請只問:)
試試這個'var query = ctn.Inventory..Include(「Shops」)。其中(ic =>!ic.Deleted && ic.ShopID == reportRequest.ShopID);'這會在查詢中添加相應的更改到數據庫。 – Saravanan 2013-05-12 14:25:03
@saravanan感謝您的回覆。我曾試圖太沒有結果:S – 109221793 2013-05-12 15:05:56
作爲格特·阿諾德指出,是否包含在上下文中的產品。您是否碰巧調試過代碼並獲取了相應關聯中的值。 – Saravanan 2013-05-12 16:24:31