EF6 entity mapping. join / navigation property
I have a fairly standard setup using fluent API
Student - entity
StudentId
Name
Course - entity
CourseId
Name
So this is represented quite easily as two entities Student and course with a virtual many to many.
Which creates the below table :
StudentCourse
CourseId
StudentId
For each Course a student is on I want to be able to set a status . e.g. Completed, in progress, etc.
Normally I would put this in the StudentCourse table.
How do I do this in EF?
then if I want to list a students courses I would access the Students.Courses property.
As part of this list I want to see the students status, but status isn't a property on course, how do I represent this?
Re: EF6 entity mapping. join / navigation property
Mapping a junction table on a many to many relationship using Fluent API would normally look something like this.
Code:
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.Courses).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("Enrolments");
});
I am not a big user of Fluent API but AFAIK your cannot do this on a many to many fluent mapping. If you add additional field to the junction table and you want to access that field in the application you need to create your junction table as an entity instead.
I am not sure exactly what your code looks like but you can do something like this;
Code:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public virtual ICollection<Enrolment> Enrolments { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
public virtual ICollection<Enrolment> Enrolments { get; set; }
}
public class Enrolment
{
public int StudentId { get; set; }
public int CourseId { get; set; }
public string Status { get; set; }
public virtual Course Course{ get; set; }
public virtual Student Student { get; set; }
}
Then you can use fluent api to map the compound key on the enrolment table.
Code:
modelBuilder.Entity<Enrolment>().HasKey(e => new { e.StudentId, e.CourseId });