我的情況是產品有一個庫存。所以我在Stocks表上添加了ProductId。表中有這樣的記錄:ASP.NET MVC一對一關聯數據不會顯示在索引頁面
產品表:
ID |名稱|說明| SellingPrice
--------------------------------------------- ---
1 | product1 | desc | 10.20
2 | product2 | prod desc | 20.55
--------------------------------------------- ---
庫存表:
ID | ProductId |數量
--------------------------------------------- ---
1 | 1 | 100
2 | 2 | 250
--------------------------------------------- ---
現在在產品索引頁,我想這樣的顯示在HTML表中的數據:
<table border="1">
<tr>
<th>Name</th>
<th>Description</th>
<th>Selling Price</th>
<th>Stock</th>
</tr>
<tr>
<td>product1</td>
<td>desc</td>
<td>10.20</td>
<td>100 (Note: I cannot see stock data when i open products index, this is what i want to see)</td>
</tr>
<tr>
<td>product2</td>
<td>product desc</td>
<td>20.55</td>
<td>250 (Note: I cannot see stock data when i open products index, this is what i want to see)</td>
</tr>
</table>
下面是MVC代碼,我已經做至今:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public Decimal SellingPrice { get; set; }
public virtual Stock Stock { get; set; }
}
public class Stock
{
public int Id { get; set; }
public int Qty { get; set; }
public int ProductId { get; set; }
[Required]
public virtual Product Product { get; set; }
}
// GET: Products
public ActionResult Index()
{
var products = db.Products.ToList();
return View(products);
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.SellingPrice)
</th>
<th>@Html.DisplayNameFor(model => model.Stock)</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.SellingPrice)
</td>
<td>
@Html.DisplayFor(modelItem => item.Stock.Qty)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
@ Html.DisplayFor(modelItem => item.Stock.Qty這段代碼沒有返回任何記錄,這就是爲什麼我在產品索引頁上看不到股票數據。任何幫助將不勝感激,謝謝!
這裏有附件,生成表格的截圖在SQL
我想你應該在公共虛擬股票上面添加'[ForeignKey(「StockId」)]'get;組; }'。在SQL Server中生成你的表格的截圖。 – Spectarion
謝謝爺爺,讓我檢查一下。 – newbie
添加[ForeignKey]數據註釋後,請確保重新生成數據庫。我相信它不知道如何創建一個適當的關係,因爲你不是先遵循代碼[約定](https://msdn.microsoft.com/en-us/library/jj679962(v = vs.113).aspx )。 – Spectarion