【发布时间】:2017-07-28 10:28:07
【问题描述】:
我的情况是产品有一个库存。所以我在 Stocks 表上添加了 ProductId。表有这样的记录:
产品表:
标识 |姓名 |说明 |售价
----------------------------------- -
1 |产品1 |描述 | 10.20
2 |产品2 |产品描述 | 20.55
----------------------------------- -
库存表:
标识 |产品编号 |数量
----------------------------------- -
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生成表的截图
【问题讨论】:
-
我认为您应该在
public virtual Stock Stock { get; set; }上方添加[ForeignKey("StockId")]。为您在 SQL Server 中生成的表截屏。 -
谢谢爷爷,让我检查一下。
-
确保在添加 [ForeignKey] 数据注释后重新生成数据库。我相信它不知道如何建立适当的关系,因为您没有先遵循代码conventions。
-
更新数据库后,它在 PM 控制台上引发以下错误:类型“IMS.Models.Product”的属性“Stock”上的 ForeignKeyAttribute 无效。在依赖类型“IMS.Models.Stock”上找不到外键名称“StockId”。 Name 值应该是一个逗号分隔的外键属性名称列表。
-
另外,你应该添加这个:
public virtual int StockId { get; set; }。 Check this out
标签: asp.net asp.net-mvc asp.net-mvc-5 entity-framework-6