“Null”外键关系在MVC3 + EF上创建记录

时间:2012-07-12 06:42:42

标签: asp.net-mvc-3 razor

我正在使用EF + MVC3 + razor 我的userProfile模型类有一个Name,Surname变量+一个外键Hobby(因为我想把它看成一个下拉列表) 我创建了一个控制器,只需选择这个clase和Data Context。

当我尝试创建记录时,它不会让我,正如它在验证区域中所说的那样:“Hobby字段是必需的。” 我希望不需要“爱好”下拉菜单。 我该怎么做呢?!..

这就是我所拥有的:

型号:

public class UserProfile    {
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Surname { get; set; }

    public int HobbiesId { get; set; }
    public virtual Hobby Hobby { get; set; }}

public class Hobby
{
    public int HobbiesId { get; set; }
    public string HobbieName { get; set; }
    public virtual ICollection<UserProfile> UserProfiles { get; set; } 
}

 public class UserProfileDBContext : DbContext
{
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Hobby> Hobbies{ get; set; }
 }

查看:

[..]@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>UserProfile</legend>

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

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

    <div class="editor-label">
        @Html.LabelFor(model => model.HobbyId, "Hobby")
    </div>
    <div class="editor-field">
        @Html.DropDownList("HobbyId", String.Empty)
        @Html.ValidationMessageFor(model =>  model.HobbyIdId)
    </div>
[..]

控制器的创建是:

   [HttpPost]
    public ActionResult Create(UserProfile userprofile)
    {
        if (ModelState.IsValid)
        {
            db.UserProfiles.Add(userprofile);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        ViewBag.HobbyId = new SelectList(db.Hobbies, "HobbyId", "Hobby", userprofile.HobbyId);
 return View(userprofile); }

我已经尝试修改:

 public class Hobby
{
    public int ?HobbiesId { get; set; }

但它不起作用。

有任何帮助吗?..

提前致谢!..

即插即用

1 个答案:

答案 0 :(得分:1)

添加外键约束,如下所示:

 public int? HobbiesId { get; set; }
 [ForeignKey("HobbiesId")]