Reputation: 5705
I have two tables:
Products:
ProductID, ProductName
Compounds:
CompoundID, ComponentID, Qty
bound as next:
1 Products.ProductID --> many Compounds.CompoundID
1 Products.ProductID --> many Compounds.ComponentID
A Products item can be a compound, a components, or both.
I need that a view returns for each compound its components names and Quatities.
MyController method :
public ActionResult CompoundProduct()
{
var Compounds = db.Compounds.Include(s => s.Products);
return View(Compounds.ToList());
}
MyView code : @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>
With this method I get a list of repeated Compound name instead of distinct Component names per Compound as shown in the image below:
any help please ?
Upvotes: 0
Views: 231
Reputation: 177163
When you created the model from the database EF should have created two navigation properties Products
and Products1
related to the two foreign keys CompoundID
and ComponentID
. You are probably using the wrong navigation property that belongs to CompoundID
, not the one that belongs to ComponentID
. Instead of Products
try to use Products1
in the Include
...
var Compounds = db.Compounds.Include(s => s.Products1);
...and in the view:
@Html.DisplayFor(modelItem => item.Products1.ProductName)
Upvotes: 1