MvcScaffolding one-many relationship

こ雲淡風輕ζ 提交于 2020-01-24 10:05:07

问题


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?


回答1:


I think you also need to have a property CategoryID on your Product class. It won't be virtual because you want EntityFramework to persist it in the DB as the foreign key.

Try adding it and scaffold them again to see if it gives you the drop down. You're right in thinking it should.

Also convention is that ID fields will be keys so I don't think you need the [Key] attributes.



来源:https://stackoverflow.com/questions/10100332/mvcscaffolding-one-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!