3

I'm using MVC 4, EF 4.3 and the MVCScaffolding package.

I have following simple model classes

 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; }
}

I scaffolded out the controllers like so:

Scaffold Controller Category -Force 
Scaffold Controller Product -Force 

This generated the controllers/views etc.

Per Steve sanderson's post I would think that the _CreateOrEdit.cshtml for the Product would contain a dropdown for the Category but it does not.

Followng are the contents of the _CreateOrEdit.cshtml and it does not contain any html template for the Category

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

What am I doing wrong?

4

1 回答 1

3

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

尝试添加它并再次为它们搭建脚手架,看看它是否为您提供了下拉菜单。你认为它应该是正确的。

另外约定是 ID 字段将是键,所以我认为您不需要 [Key] 属性。

于 2012-04-11T11:19:30.037 回答