RobertStettler RobertStettler - 3 months ago 16
C# Question

Relationship logic in MVC asp.net for 1-many for code first EF

I get a little confused with the code first logic in EF asp.net mvc. The example on the asp.net page says, that for this database structure
Example Database for Student and Course with intermediate table enrollment

public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }
}


public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }

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


Why do I need to specify in the model for the student the enrollment? Isn't the SQL relationship already defined in the enrollment, i.e. I could (without EF asp.net) get all coureses for one student by doing something like

SELECT course.Title FROM enrollment, course WHERE enrollment.student = studentID AND course.courseID = enrollment.CourseID


here I don't need any information about the enrollment in the student table. Why do I need it in the MVC EF setup?

Answer Source

The intent of the navigation property is to make the relation transparent in your Student object and also let you find all enrollments for a student with a simple query like:

// get all enrolments for Sutdent with certain Id
    var enrolments = context.Students
        .FirstOrDefault(s => s.ID == studentId)?.Enrollments?.ToList();

// get all courses for a student
    var courses = context.Courses
        .Include(x => x.Enrollments)
        .SelectMany(c => c.Enrollments)
        .Where(e => e.StudentID == studentId)
        .ToList();

"In Entity Framework, an entity can be related to other entities through an association (relationship). Each relationship contains two ends that describe the entity type and the multiplicity of the type (one, zero-or-one, or many) for the two entities in that relationship. The relationship may be governed by a referential constraint, which describes which end in the relationship is a principal role and which is a dependent role.

Navigation properties provide a way to navigate an association between two entity types. Every object can have a navigation property for every relationship in which it participates. Navigation properties allow you to navigate and manage relationships in both directions, returning either a reference object (if the multiplicity is either one or zero-or-one) or a collection (if the multiplicity is many). You may also choose to have one-way navigation, in which case you define the navigation property on only one of the types that participates in the relationship and not on both." https://msdn.microsoft.com/en-us/library/jj713564(v=vs.113).aspx