我有两张桌子:
产品:
ProductID,ProductName
化合物:
CompoundID,ComponentID,Qty
绑定为下一个:
1个产品。 ProductID - >许多化合物。 CompoundID
1个产品。 ProductID - >许多化合物。 ComponentID
产品项目可以是化合物,组件或两者。
我需要一个视图为每个化合物返回其组件名称和Quatities。
MyController方法:
public ActionResult CompoundProduct()
{
var Compounds = db.Compounds.Include(s => s.Products);
return View(Compounds.ToList());
}
MyView代码: @model IEnumerable
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CompoundID)
</td>
<td>
@Html.DisplayFor(modelItem => item.ComponentID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Products.ProductName)
</td>
</tr>
}
</table>
使用此方法,我得到一个重复的化合物名称列表,而不是每个化合物的不同组件名称,如下图所示:
有什么帮助吗?
答案 0 :(得分:1)
当您从数据库创建模型时,EF应该创建与两个外键Products
和{{}相关的两个导航属性Products1
和CompoundID
1}}。您可能正在使用属于ComponentID
的错误导航属性,而不是属于CompoundID
的导航属性。而不是ComponentID
尝试在Products
...
Products1
Include
......并且在视图中:
var Compounds = db.Compounds.Include(s => s.Products1);