EntityFramework Code-First 簡易教程(十)-------多對多

配置Many-to-Many(多對多)關係:

這裏有兩個類,Student和Course,一個Student能夠有多個Course,一個Course也能夠有多個Student,因此這就成了多對多關係。更多信息請訪問Entity Relationship數據庫

 

進入正題:ide

1.使用DataAnnotation配置多對多關係:

Student類中有一個Course的集合屬性,在Course類中也有一個Student的集合屬性,這樣就默認配置成了多對多關係。代碼以下:ui

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

    public int StdandardId { get; set; }
        
    public virtual ICollection<Course> Courses { get; set; }
}
        
public class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

上面的代碼將會建立以下的數據庫,這裏會新建一張表CourseStudents,這張新表裏面記錄着對多對關係的兩個表的外鍵StudentId和CourseId(固然在CourseStudents表中這兩列便是主鍵又是外鍵)。this

one-to-one relationship in code first

2.使用Fluent API配置多對多關係:

直接上配置代碼:spa

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentRefId");
                            cs.MapRightKey("CourseRefId");
                            cs.ToTable("StudentCourse");
                        });

}

 

如你所見,上面的例子中, .HasMany<Course>(s => s.Courses).WithMany(c => c.Students) 告訴Student和Course有多對多關係。.net

Map方法能夠傳入一個委託,因此這裏能夠使用lambda表達式,其中,MapLeftKey方法指定了Student的外鍵屬性名稱(這裏先指定Student,因此它是左表)和Course表的外鍵,ToTable方法將建立StudentCourse表。code

這樣數據庫將會建立一個新表StudentCourse,CourseRefId和StudentRefId既是主鍵又是外鍵。blog

one-to-one relationship in code first

 

 

到此,一對一,一對多,多對多的關係咱們就講完了,基本上能應對大多數狀況的開發了。ip

相關文章
相關標籤/搜索