AWD-Lecture 05 EFCRel
AWD-Lecture 05 EFCRel
Relationships
Student Class
Course Class
}
Many-to-Many Relationship
• After we implement the many to many relationship the following
changes must be made in both classes.
}
Many-to-Many Relationship
• Now the time is for adding the bridge entity class.
• The intermediate class name is StudentCourse.
• With following properties.
public class StudentCourse
{
[ForeignKey("Student")]
public int StudentId { get; set; }
[ForeignKey("Course")]
public int CourseId { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
}
Many-to-Many Relationship
• As the StudentCourse class primary key may be the combination of
the tow fileds which are studentId and CourseId.
• The data annotation dose not have any method for composite key so
for this purpose we should use the fluent api to configure composite
key for this model class.
•
• modelBuilder.Entity<Customer>()
• .HasOne(f => f.Country)
• .WithMany(f => f.Customers)
• .HasForeignKey(f => f.MyID);
Fluent API many-to-many relationship
• modelBuilder.Entity<StudentCourse>()
• .HasKey(k => new { k.StudentId, k.CourseId });
• modelBuilder.Entity<StudentCourse>()
• .HasOne(s => s.Student)
• .WithMany(sc => sc.StudentCourses)
• .HasForeignKey(sf => sf.StudentId);
• modelBuilder.Entity<StudentCourse>()
• .HasOne(c => c.Course)
• .WithMany(sc => sc.StudentCourses)
• .HasForeignKey(cf => cf.CourseId);
Fluent API Organization
• public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
• {
• public void Configure(EntityTypeBuilder<Customer> builder)
• {
• builder.HasKey(c => c.Id);
• }
• }
• modelBuilder.ApplyConfiguration(new CustomerConfiguration());
Its your turn to ask about today’s lecture