MvcScaffolding一对多关系 [英] MvcScaffolding one-many relationship

查看:86
本文介绍了MvcScaffolding一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC 4,EF 4.3和MVCScaffolding软件包.

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

我有以下简单的模型类

 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.

史蒂夫·桑德森的帖子会认为该产品的_CreateOrEdit.cshtml将包含类别"的下拉列表,但没有.

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.

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

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>

我在做什么错了?

推荐答案

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

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.

还有一个约定,ID字段将是键,因此我认为您不需要[Key]属性.

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

这篇关于MvcScaffolding一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆