Entity Framework little knowledge (5)

Time:2022-11-24

existMany-to-many relationship mappingThe middle association table is automatically generated by EF. But sometimes we need to display the definition association table. We can define it in the following steps (continue to use the many-to-many relationship mapping article to starve the code):

  1. Define the association table class:
public class StudentCourses : BaseEntity
{
    public int StudentId { get; set; }
    public virtual Student Student { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
}
  1. ReviseStudentandCoursesNavigation property in class:
public class Student:BaseEntity
{
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual ICollection<StudentCourses> StudentCourses { get; set; }
}

public class Course : BaseEntity
{
    public string Name { get; set; }
    public string TeacherName { get; set; }
    public virtual ICollection<StudentCourses> StudentCourses { get; set; }
}
  1. ReviseStudentMapandCoursesMapmapping:
public class StudentsMap : EntityTypeConfiguration<Student>
{
    public StudentsMap()
    {
        //table name
        ToTable("Students");
        //primary key
        HasKey(p => p.Id);

        // Set the primary key to grow
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        //Set the data to be mapped
        Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
        Property(p => p.Age);
        Property(p => p.CreateDateTime);

        // set the relationship
        HasMany(p => p.StudentCourses)
            .WithRequired(p => p.Student)
            .HasForeignKey(p => p.StudentId);

    }
}

public class CourseMap : EntityTypeConfiguration<Course>
{
    public CourseMap()
    {
        ToTable("Coureses");
        HasKey(p => p.Id);
        Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
        Property(p => p.TeacherName);
        Property(p => p.CreateDateTime);

        HasMany(p => p.StudentCourses)
            .WithRequired(p => p.Course)
            .HasForeignKey(p => p.CourseId);
    }
}

Run the code, check the database and find that the same database is generated, and the many-to-many relationship is also correctly reflected.