首先在代码中添加ASP.NET MVC中的外键

时间:2015-03-13 11:34:58

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

我想在讲师和课程之间建立一对多的关系。我怎样才能实现它?以下是我现在的情况。

public class Instructor
{
    //[Key]
    public int id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
    public string email { get; set; }
}
public class Course
{
    //[Key]
    public int id { get; set; }
    [DisplayName("Course")]
    [Required(ErrorMessage = "CSExxx")]
    public string progId { get; set; }
    public string name { get; set; }
    public string semester { get; set; }
    public string description { get; set; }
    public virtual Instructor instructor { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您需要向教师添加课程的虚拟集合

public class Instructor
{
    //[Key]
    public int id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
    public string email { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
    //[Key]
    public int id { get; set; }
    [DisplayName("Course")]
    [Required(ErrorMessage = "CSExxx")]
    public string progId { get; set; }
    public string name { get; set; }
    public string semester { get; set; }
    public string description { get; set; }
    public virtual Instructor instructor { get; set; }
}

在DataContext中的OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Instructor>().HasMany(i => i.Courses).WithRequired(c => c.Instructor).HasForeignKey(c => c.instructor).WillCascadeOnDelete(true);
}