Create a Foreign Key relationship using Code First Entity Framework In asp.net MVC4

In this post I will explain How to create Foreign Key relationship in  Entity Framework(EF).

When you create a model of relation database some time we got following error
Unable to retrieve association information for association 'Models.Product_Parent'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information.

         I will explain how to create Model class for following  relation data base
First create a model class for Student table


public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class CourseSelection
{
    [Key]
    public int CourseSelectionID { get; set; }
    public string CourseID { get; set; }
    public int StudentID { get; set; }
}

public class Course
{
    [Key]
    public string CourseID { get; set; }
    public String CourseName { get; set; }
}
  Now I just create a Model class with out relation ship .Now I will explain How to set ForeighKeyAttribute of above model class  bellow.In Above table student and Course table have only primary key.But Course Selection table have Foreign key studentId and CourseId so we rewrite Course Selection class to bellow format

public class CourseSelection
{
    [Key]
    public int CourseSelectionID { get; set; }
    ForeignKey("Course ")]
    public string CourseID { get; set; }
    public virtual Cource course { get; set; }
    [ForeignKey("Student ")]
    public int StudentID { get; set; }
    public virtual Student Student { get; set; }
}

3 comments:

  1. public virtual Student course { get; set; } ?

    or

    public virtual Course course { get; set; } ?

    ReplyDelete
  2. yes this is public virtual Course course { get; set; }

    ReplyDelete
  3. Excellent example but fix:

    public virtual Student course { get; set; } to public virtual Course course { get; set; }

    That is the correct form.

    ReplyDelete