标签 标签 标签
- 一句话的事儿:
关系图
数据库表的体现
- 一个俱乐部对应一个联赛
多对多的关系
简单说明:
一个队员Player可以参加多场比赛,同时一场比赛又有多个队员来参加,这就形成多对多的关系;由于EFCore不能直接实现多对多的关系,那么我们这借助中间表GamePlayer来实现多对多的关系.
一个队员参加了多少场比赛,即1:m;
一场比赛中对应多个队员,即1:n;
那么队员于比赛之间的换算公式就是:m:n
01.首先创建Game
补充说明:构造函数是为了避免空指针异常发生。
public class Game
{
public Game()
{
GamePlayers = new List<GamePlayer>();
}
public int Id { get; set; }
//轮次
public int Round { get; set; }
public DateTimeOffset? StartTime { get; set; }
public List<GamePlayer> GamePlayers { get; set; }
}
02.重写Player
public class Player
{
public Player()
{
GamePlayers = new List<GamePlayer>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public List<GamePlayer> GamePlayers { get; set; }
}
03.创建中间表GamePlayer
public class GamePlayer
{
//此处GamPlayer本应有自己的主键,这里我们采用联合主键的办法,
//联合主键,即PlayerId+GameId
public int PlayerId { get; set; }
public int GameId { get; set; }
public Game Game { get; set; }
public Player Player { get; set; }
}
04.为中间表GamePlayer创建联合主键
补充说明:在DataContext中重写onModelCreating()
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
}
05.再次迁移数据Add-Migration AddGameetc.
06.Update-Database
一对一的关系图
01.新建Resume
public class Resume
{
public int Id { get; set; }
public string Description { get; set; }
public int PlayerId { get; set; }
public Player Player { get; set; }
}
02.重写Player
public class Player
{
public Player()
{
GamePlayers = new List<GamePlayer>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public List<GamePlayer> GamePlayers { get; set; }
public int ResumeId { get; set; }
public Resume Resume { get; set; }
}
03.既然是一对一的关系,EFCore需要知道哪个主哪个是辅
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
modelBuilder.Entity<Resume>()
.HasOne(x => x.Player)
.WithOne(x => x.Resume)
.HasForeignKey<Resume>(x => x.PlayerId);
}
04.ADD-Migration OneToOne->Update-Database
- 本文作者:GeekPower - Felix Sun
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!