2013-03-11 70 views
0

我有两个表:实体框架 - 包括返回错误结果

产品:
产品ID,产品名称

化合物:

CompoundID,的ComponentID,数量

绑定为下一个:

1个相关产品。 产品编号 - >许多化合物。 化合物ID

1个产品。 产品编号 - >许多化合物。 ComponentID

产品项目可以是化合物,组分或两者。

我需要一个视图为每个化合物返回其组件名称和数据。

方法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> 

使用这种方法,我得到重复组合名称的列表,而不是每复方不同组件名称如图所示图片如下: enter image description here

请帮忙吗?

+0

你在哪里得到的化合物名称? – IronMan84 2013-03-11 16:48:45

+0

化合物和组分名称均来自产品表**产品名称字段**。 – 2013-03-11 16:52:45

+0

你可以显示实体类和映射吗? – Slauma 2013-03-11 17:50:08

回答

1

当您创建从数据库EF模型应创建相关的两个外键CompoundIDComponentID 导航属性ProductsProducts1。您可能正在使用属于CompoundID的错误导航属性,而不属于ComponentID。取而代之的Products尝试在Include使用Products1 ...

var Compounds = db.Compounds.Include(s => s.Products1); 

...并在视图:

@Html.DisplayFor(modelItem => item.Products1.ProductName)