标签:shm 配置 foreign 实例化 elb bilibili 需要 注意 列表
此入门教程是记录下方参考资料视频的过程,本例基于Entity Framework Core 3.1
开发工具:Visual Studio 2019
public class Resume
{
public int Id { get; set; }
public string Description { get; set; }
//外键
public int PlayerId { get; set; }
//导航属性,可以不写,但是建议写一对
public Player Player { get; set; }
}
//先添加 DbSet
public DbSet<Resume> Resumes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Entity<T>,T填谁都可以
//HasForeignKey<T>,T一定要是外键在的表
modelBuilder.Entity<Resume>().HasOne(x => x.Player)
.WithOne(x => x.Resume)
.HasForeignKey<Resume>(x => x.PlayerId);
}
只需要在一个类中体现就可以了,比如:一个League对应多个Club,Club中的League属性就能体现一对多
或者使用List<>集合,比如,一个Club对应多个Player,Club中的List
Entity Framework Core会自动生成外键
public class League
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
public class Club
{
public Club()
{
//实例化列表,防止空指针异常
this.Players = new List<Player>();
}
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
//成立日期
public DateTime DateOfEstablishment { get; set; }
//比较长的描述性文字
public string History { get; set; }
//实体关系在此处建立联系
public League League { get; set; }
public List<Player> Players { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Game
{
public Game()
{
this.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; }
}
这里我使用方案二
public class GamePlayer
{
public int PlayerId { get; set; }
public Player Player { get; set; }
public int GameId { get; set; }
public Game Game { get; set; }
}
注意:这是多对多的中间表,主键无所谓,使用GameId和PlayerId做联合主键(不推荐,主键标识还是需要的)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Entity<T>,T填中间表
modelBuilder.Entity<GamePlayer>().HasKey(x => new { x.PlayerId, x.GameId });
}
EF Core 5.0的多对多有机会就写一篇
Entity Framework Core 3.1 入门(三)一对一、多对多
标签:shm 配置 foreign 实例化 elb bilibili 需要 注意 列表
原文地址:https://www.cnblogs.com/zzy-tongzhi-cnblog/p/14366894.html