标签 标签 标签

  • 一句话的事儿:

关系图

image.png
即一个联赛可以有多个足球队俱乐部,一个俱乐部有多个足球队员

数据库表的体现

  • 一个俱乐部对应一个联赛

image.png

多对多的关系

image.png
简单说明:
一个队员Player可以参加多场比赛,同时一场比赛又有多个队员来参加,这就形成多对多的关系;由于EFCore不能直接实现多对多的关系,那么我们这借助中间表GamePlayer来实现多对多的关系.
一个队员参加了多少场比赛,即1:m;
一场比赛中对应多个队员,即1:n;
那么队员于比赛之间的换算公式就是:m:n

01.首先创建Game

补充说明:构造函数是为了避免空指针异常发生。

  1. public class Game
  2. {
  3. public Game()
  4. {
  5. GamePlayers = new List<GamePlayer>();
  6. }
  7. public int Id { get; set; }
  8. //轮次
  9. public int Round { get; set; }
  10. public DateTimeOffset? StartTime { get; set; }
  11. public List<GamePlayer> GamePlayers { get; set; }
  12. }

02.重写Player

  1. public class Player
  2. {
  3. public Player()
  4. {
  5. GamePlayers = new List<GamePlayer>();
  6. }
  7. public int Id { get; set; }
  8. public string Name { get; set; }
  9. public DateTime DateOfBirth { get; set; }
  10. public List<GamePlayer> GamePlayers { get; set; }
  11. }

03.创建中间表GamePlayer

  1. public class GamePlayer
  2. {
  3. //此处GamPlayer本应有自己的主键,这里我们采用联合主键的办法,
  4. //联合主键,即PlayerId+GameId
  5. public int PlayerId { get; set; }
  6. public int GameId { get; set; }
  7. public Game Game { get; set; }
  8. public Player Player { get; set; }
  9. }

04.为中间表GamePlayer创建联合主键

补充说明:在DataContext中重写onModelCreating()

  1. protected override void OnModelCreating(ModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
  4. }

05.再次迁移数据Add-Migration AddGameetc.

image.png

06.Update-Database

image.png

一对一的关系图

image.png
补充说明:
每一个队员都一份自己的简历Resume

01.新建Resume

  1. public class Resume
  2. {
  3. public int Id { get; set; }
  4. public string Description { get; set; }
  5. public int PlayerId { get; set; }
  6. public Player Player { get; set; }
  7. }

02.重写Player

  1. public class Player
  2. {
  3. public Player()
  4. {
  5. GamePlayers = new List<GamePlayer>();
  6. }
  7. public int Id { get; set; }
  8. public string Name { get; set; }
  9. public DateTime DateOfBirth { get; set; }
  10. public List<GamePlayer> GamePlayers { get; set; }
  11. public int ResumeId { get; set; }
  12. public Resume Resume { get; set; }
  13. }

03.既然是一对一的关系,EFCore需要知道哪个主哪个是辅

  1. protected override void OnModelCreating(ModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
  4. modelBuilder.Entity<Resume>()
  5. .HasOne(x => x.Player)
  6. .WithOne(x => x.Resume)
  7. .HasForeignKey<Resume>(x => x.PlayerId);
  8. }

04.ADD-Migration OneToOne->Update-Database


  • 本文作者:GeekPower - Felix Sun
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!