1、定義模型
示例:學生和桌子的一對一關系:每個學生需要對應一個桌位信息,桌位信息不用包含學生信息
public class Desk { public int Id { get; set; } public string Name { get; set; } public Student Student { get; set; } }
public class Student { public int Id { get; set; } public string Name { get; set; } public int DeskID { get; set; } public Desk Desk { get; set; } }
在Student中定義 DeskID和Desk模型,在Desk表中定義Student模型
2、在DataContext中定義兩者的關系
protected override void OnModelCreating(ModelBuilder modelBuilder) { // Do:一對一關系模型 modelBuilder.Entity<Student>().HasOne(l => l.Desk).WithOne(l => l.Student) .HasForeignKey<Student>(l => l.DeskID); }
public DbSet<Student> Students { get; set; }
public DbSet<Desk> Desks { get; set; }
此時通過遷移命令將會生成Students表和Desks表
1、定義模型
示例:學校和老師的一對多關系:一個學校對應多個老師,一個老師對應一個學校
public class School { public int Id { get; set; } public string Name { get; set; } public List<Teacher> Teachers { get; set; } }
public class Teacher { public int Id { get; set; } public string Name { get; set; } public int SchoolID { get; set; } public School School { get; set; } }
2、在DataContext中定義兩者的關系
protected override void OnModelCreating(ModelBuilder modelBuilder) { // Do:一對多關系模型 modelBuilder.Entity<Teacher>().HasOne(l => l.School).WithMany(l => l.Teachers) .HasForeignKey(l => l.SchoolID); } public DbSet<Teacher> Teachers { get; set; } public DbSet<School> Schools { get; set; }
此時通過遷移命令將會生成Schools表和Teachers表
五、多對多的關系模型
1、定義模型:
示例:建立父母和孩子的多對多模型,父母可以對應多個孩子,孩子可以有父親,母親的對應關系
// Do:定義父母類型 public class Parent { public Parent() { this.RelationShips =new List<RelationShip>(); } public int Id { get; set; } public string Name { get; set; } // Do:3、定義關系集合 public List<RelationShip> RelationShips { get; set; } }
// Do:定義子類型 public class Child { public Child() { this.RelationShips=new List<RelationShip>(); } public int Id { get; set; } public string Name { get; set; } // Do:2、定義關系集合 public List<RelationShip> RelationShips { get; set; } }
/// <summary> /// 1、多對多關系模型 /// </summary> public class RelationShip { public int ChildID { get; set; } public Child Child { get; set; } public int ParentID { get; set; } public Parent Parent { get; set; } }
2、在DataContext中定義兩者的關系
protected override void OnModelCreating(ModelBuilder modelBuilder) { // Do:多對多配置聯合主鍵 modelBuilder.Entity<RelationShip>().HasKey(l => new {l.ChildID, l.ParentID}); // Do:多對多定義關系模型映射(本段代碼可有可無) modelBuilder.Entity<RelationShip>().HasOne(l => l.Child).WithMany(l => l.RelationShips) .HasForeignKey(l => l.ChildID); modelBuilder.Entity<RelationShip>().HasOne(l => l.Parent).WithMany(l => l.RelationShips) .HasForeignKey(l => l.ParentID); } public DbSet<Teacher> Teachers { get; set; } public DbSet<School> Schools { get; set; }