EntityFrameworkCore 一對一 && 一對多 && 多對多配置

基本數據結構

default
表設計以下:
入學記錄git

public class AdmissionRecord
{
    [Key]
    public long Id { get; set; }
    public DateTime AdmissionTime { get; set; }
    public string Remark { get; set; }
}

班級github

public class Class
{
    [Key]
    public long Id { get; set; }
    public DateTime CreationTime { get; set; }
    public string ClassName { get; set; }
    public virtual List<Student> Students { get; set; }
}

學生-教師關係表c#

public class StudentTeacherRelationship
{
    [Key]
    public long Id { get; set; }
    public long StudentId { get; set; }
    public virtual Student Student { get; set; }
    public long TeacherId { get; set; }
    public virtual Teacher Teacher { get; set; }
}

教師數據結構

public class Teacher
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
    public string TeacherId { get; set; }
    public virtual List<StudentTeacherRelationship> StudentTeacherRelationships { get; set; }
}

學生ui

public class Student
{
    [Key]
    public long Id { get; set; }
    public string StudentId { get; set; }
    public string Name { get; set; }
    public long AdmissionRecordId { get; set; }
    //Student-AdmissionRecord 1:1
    [ForeignKey("AdmissionRecordId")]
    public virtual AdmissionRecord AdmissionRecord { get; set; }
    public long ClassId { get; set; }
    public virtual Class Class { get; set; }
    public virtual List<StudentTeacherRelationship> StudentTeacherRelationships { get; set; }
}

一對一

學生-入學記錄設計

public long AdmissionRecordId { get; set; }
//Student-AdmissionRecord 1:1
[ForeignKey("AdmissionRecordId")]
public virtual AdmissionRecord AdmissionRecord { get; set; }

另解code

modelBuilder.Entity<Student>()
    .HasOne(p => p.AdmissionRecord)
    .WithOne(p => p.Student)
    .HasForeignKey<Student>(p => p.AdmissionRecordId);

參考資料:
Configuring One To One Relationships In Entity Framework Coreblog

一對多

學生-班級ip

modelBuilder.Entity<Class>()
    .HasMany(p => p.Students)
    .WithOne(p => p.Class)
    .HasForeignKey(p => p.ClassId)
    .OnDelete(DeleteBehavior.ClientSetNull);
//下面寫法也能夠
//modelBuilder.Entity<Student>()
//    .HasOne(p => p.Class)
//    .WithMany(p=>p.Students)
//    .HasForeignKey(k => k.ClassId)
//    .OnDelete(DeleteBehavior.ClientSetNull);

多對多

學生-教師get

//經過StudentTeacherRelationship中間表,經過實現兩個1:n,實現m:n
modelBuilder.Entity<StudentTeacherRelationship>()
    .HasOne(p => p.Student)
    .WithMany(p => p.StudentTeacherRelationships)
    .HasForeignKey(k => k.StudentId)
    .OnDelete(DeleteBehavior.ClientSetNull);

modelBuilder.Entity<StudentTeacherRelationship>()
    .HasOne(p => p.Teacher)
    .WithMany(p => p.StudentTeacherRelationships)
    .HasForeignKey(k => k.TeacherId)
    .OnDelete(DeleteBehavior.ClientSetNull);

示例代碼

示例代碼

相關文章
相關標籤/搜索