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
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 Student course { get; set; }
[ForeignKey("Student ")]
public int StudentID { get; set; }
public virtual Student Student { get; set; }
}
|

No comments:
Post a Comment