C# 实体框架6.1韩元';不创建连接表
作为一个学习练习,我正在尝试创建一个国际象棋网站。我正在使用EntityFramework6.1来存储记录,但在创建迁移时遇到了困难,这与我所认为的应该是一样的 我希望能够检索一个玩家和该玩家玩过的所有游戏的列表C# 实体框架6.1韩元';不创建连接表,c#,entity-framework-6,C#,Entity Framework 6,作为一个学习练习,我正在尝试创建一个国际象棋网站。我正在使用EntityFramework6.1来存储记录,但在创建迁移时遇到了困难,这与我所认为的应该是一样的 我希望能够检索一个玩家和该玩家玩过的所有游戏的列表 public class Game { public int Id { get; set; } // Other Properties public virtual Player White { get; protected set; } public
public class Game
{
public int Id { get; set; }
// Other Properties
public virtual Player White { get; protected set; }
public virtual Player Black { get; protected set; }
public Game(Player white, Player black) : this()
{
// Null checks
White = white;
Black = black;
White.Games.Add(this);
Black.Games.Add(this);
}
}
public class Player
{
public int Id { get; set; }
// Other Properties
public virtual ICollection<Game> Games { get; protected set; }
protected Player()
{
Games = new Collection<Game>();
}
}
产生了相同的迁移,我尝试了以下几种变体:
HasRequired(x => x.White)
.HasMany(x => x.Games)
.Map(t => t.ToTable("GamePlayer").MapKey("Game_Id", "Player_Id"));
HasRequired(x => x.Black)
.HasMany(x => x.Games)
.Map(t => t.ToTable("GamePlayer").MapKey("Game_Id", "Player_Id"));
在尝试生成迁移时抛出错误,抱怨游戏玩家不在模型中
如果您对我的错误有任何建议,我将不胜感激。您不可能将EF配置为使用您的模型正确填充
Player.Games
集合。这就是为什么迁移看起来与您预期的不同。没有任何方法可以告诉EF“此集合包含以白色或黑色播放的游戏”
您需要更改模型,并且有几个选项:
Player.Games
集合,添加两个集合Player.gamesplayedasbblack
,Player.GamesPlayedAsWhite
,并配置Player
和Game
实体之间的两个一对多关系GamePlayer
实体
public class Game {
public int Id { get; set; }
public virtual ICollection<GamePlayer> Players { get; set; }
}
public enum Color { White = 1, Black = 2}
public class GamePlayer {
public int Id { get; set; }
public virtual Game GamePlayed { get; set; }
public Color PlayedAs { get; set; }
public virtual Player Player { get; set; }
}
public class Player {
public virtual ICollection<GamePlayer> Games { get; set; }
}
公共类游戏{
公共int Id{get;set;}
公共虚拟ICollection播放器{get;set;}
}
公共枚举颜色{白色=1,黑色=2}
公共级玩家{
公共int Id{get;set;}
公共虚拟游戏{get;set;}
公共颜色播放为{get;set;}
公共虚拟播放器{get;set;}
}
公开课选手{
公共虚拟ICollection游戏{get;set;}
}
谢谢你的回答和解释,最后我选择了选项2。
HasRequired(x => x.White)
.HasMany(x => x.Games)
.Map(t => t.ToTable("GamePlayer").MapKey("Game_Id", "Player_Id"));
HasRequired(x => x.Black)
.HasMany(x => x.Games)
.Map(t => t.ToTable("GamePlayer").MapKey("Game_Id", "Player_Id"));
public class Game {
public int Id { get; set; }
public virtual ICollection<GamePlayer> Players { get; set; }
}
public enum Color { White = 1, Black = 2}
public class GamePlayer {
public int Id { get; set; }
public virtual Game GamePlayed { get; set; }
public Color PlayedAs { get; set; }
public virtual Player Player { get; set; }
}
public class Player {
public virtual ICollection<GamePlayer> Games { get; set; }
}