我运行一个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