I have used two ways to create one to many relationships in code first migration and I do not know what is the difference between each of them.
First method:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public Student Student { get; set; }
}
Second Method:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public Student Student { get; set; }
}
They both have the same result. See the relationship: Relationship Diagram
So why we use ICollection
in student table if we get the same relationship?
A relationship in the entity framework always has two ends, a navigation property on each side and an Entity Framework that maps them together automatically by convention.
In your example, Student and Course class have a one-to-many relationship. Here, Id (Student table) will become the primary key of the Student table and ForeignKey attributes for Student_Id property in Course class in order to make foreign key.You have to pass Student entity in ForeignKey attribute of Course class. Thus, the code first creates a one-to-many relation between Student and Course class using DataAnnotations attributes.
For Example:
You can simple get all course Name
of a student by using negation property of student able (Courses) like:
_context.Students
.Include(s => s.Courses)
.Courses.Select(c=>c.Name).ToList();
You can fiend more information about One-to-Many this link.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments