MvcScaffolding一对多关系

时间:2012-04-11 05:30:34

标签: asp.net-mvc asp.net-mvc-scaffolding

我正在使用MVC 4,EF 4.3和MVCScaffolding包。

我有以下简单的模型类

 public class Product
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual Category Category { get; set; }
}
public class Category
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

我像这样搭建了控制器:

Scaffold Controller Category -Force 
Scaffold Controller Product -Force 

这会生成控制器/视图等。

Per Steve sanderson's post我认为产品的_CreateOrEdit.cshtml会包含类别的下拉列表,但事实并非如此。

Followng是_CreateOrEdit.cshtml的内容,它不包含任何类别的html模板

<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
   @Html.EditorFor(model => model.Name)
   @Html.ValidationMessageFor(model => model.Name)
</div>

我做错了什么?

1 个答案:

答案 0 :(得分:3)

我认为您还需要在Product类上拥有属性CategoryID。它不是虚拟的,因为您希望EntityFramework将其作为外键保存在DB中。

尝试添加它并再次将它们搭建以确定它是否为您提供了下拉菜单。你认为它应该是正确的。

同样惯例是ID字段是键,所以我认为你不需要[Key]属性。

相关问题