MVC 4中的实体框架 - 包括返回错误结果

时间:2013-03-11 16:15:36

标签: entity-framework asp.net-mvc-4 include

我有两张桌子:

产品:
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>

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

有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

当您从数据库创建模型时,EF应该创建与两个外键Products和{{}相关的两个导航属性Products1CompoundID 1}}。您可能正在使用属于ComponentID的错误导航属性,而不是属于CompoundID的导航属性。而不是ComponentID尝试在Products ...

中使用Products1
Include

......并且在视图中:

var Compounds = db.Compounds.Include(s => s.Products1);
相关问题