MVC4 EF6映射参数来自表单

时间:2014-01-11 00:33:09

标签: entity-framework asp.net-mvc-4

我将从视图发送的表单数据映射到它为其设计的模型类时遇到问题。

我有一个教师模型:

public class Teacher : Person
{
    [Required]
    [StringLength(50)]
    public String Title { get; set; }

    [Required]
    public DateTime DateOfApproval { get; set; }

    public ICollection<ThesisApplication> ManagerOf { get; set; }
}

和ThesisApplication模型(学生填写申请表,他说谁想成为他的经理)。

public class ThesisApplication
{
    public int Id { get; set; }

    public virtual Thesis Thesis { get; set; }

    [ForeignKey("Manager")]
    public virtual int ManagerId { get; set; }
    public virtual Teacher Manager { get; set; }

    //other properties that doesn't matter here
}

和用于它们之间连接的流畅API

modelBuilder.Entity<ThesisApplication>()
            .HasRequired( s => s.Manager ).WithMany(s => s.ManagerOf );

在我的表格中,我有:

@Html.DropDownListFor( x => x.ManagerId, (IEnumerable<SelectListItem>)( ViewBag.People  ) )

,其中

ViewBag.People = new SelectList(this.databaseEntities.Teachers.All(), "PersonId", "FirstName");

然而,当我将表单传递给我的控制器中的create方法时,就像这样

[HttpPost]
public ActionResult Create( ThesisApplication application )
{ ...

我得到了正确的managerId,但Manager属性为空(null)。当试图获取Manager的属性时抛出异常。

有人可以解释为什么会这样。 我对不使用外键的解决方案感兴趣。就像是 DropDownFor(x =&gt; x.Manager)在不使用外键的情况下映射Manager属性。

感谢:)

1 个答案:

答案 0 :(得分:0)

您从表单帖子返回的对象是一个普通对象,由实体框架在MVC模型绑定器之外实例化。如果您想要表示Teacher对象,则必须使用DbSet.Find方法(或DbSet<Teacher>中的任何其他方法):

[HttpPost]
public ActionResult Create(ThesisApplication application )
{
    using(var context = new TeacherContext()) //or whatever/however you access your DbContext
    {
        var teacher = context.Teachers.Find(application.ManagerId);
    }
}
相关问题