tanz tanz - 3 months ago 21
ASP.NET (C#) Question

Add Foreign Key in Table in ASP.NET MVC in code first

I want to have a one to many relationship in between instructor and course. How can I achieve it? Below is what I have as of now.

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

Answer

You need to add a virtual collection of Course to Instructor

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

In OnModelCreating in your DataContext

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