特定实体框架代码优先多对2模型映射
我在这里有点失落。
基本上我有这两个模型:
public class Player
{
public int PlayerId { get; set; }
public string Name { get; set; }
public virtual ICollection<Game> Games { get; set; }
}
public class Game
{
public int GameId { get; set; }
public virtual Player PlayerBlack { get; set; }
public virtual Player PlayerWhite { get; set; }
}
现在 EF Code First 为我创建的数据库架构不正确,因为游戏表有 3 个外键(Playerblack、PlayerWhite 和 Player)而不是 2 个。
那么我怎样才能将这些模型绑定在一起呢? EF 了解玩家游戏是通过查看黑人或白人玩家来找到的。
基本上每次我调用 myPlayer.Games EF 时都必须查看 PlayerBlack 和 PlayerWhite 外键。
有可能吗?
I'm a bit of a loss here.
Basically I have these two Models:
public class Player
{
public int PlayerId { get; set; }
public string Name { get; set; }
public virtual ICollection<Game> Games { get; set; }
}
public class Game
{
public int GameId { get; set; }
public virtual Player PlayerBlack { get; set; }
public virtual Player PlayerWhite { get; set; }
}
Now the Database Schema, EF Code First creates for me, is not correct because the Game table gets 3 Foreign Keys (Playerblack, PlayerWhite and Player) instead of 2.
So how can I tie these Models together so that EF understands that the Players Games are found by either looking at the Black or White Player.
Basically each time I call myPlayer.Games EF has to look into PlayerBlack AND PlayerWhite Foreign Keys.
Is it even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这是不可能的。您不能与关系一侧的单个端点和另一侧的两个端点建立关联。
可能的解决方法:
在
Player
类中使用两个集合:根据您的上下文,您也许可以将这些集合合并到一个未映射到数据库的只读集合
Games
。(编辑:建议的第二个解决方法很糟糕,现在已删除。)
Edit2:另一个解决方法可能是通过附加类
PlayerInGame
来扩展类模型:正如您可以通过
Single
Game 类中的PlayerBlack
和PlayerWhite
属性中的方法,您必须确保在业务逻辑中创建正确的PlayerInGame
实体,以便您的PlayersInGame
集合始终包含两个分别带有 Black 或 White 标志的元素。I believe it's not possible. You cannot have an association with a single endpoint on one side and two endpoints on the other side of the relation.
Possible workarounds:
Use two collections in the
Player
class:Depending on your context you could perhaps merge these collections together to a readonly collection
Games
which is not mapped to the database.(Edit: Proposed second workaround was crap, deleted now.)
Edit2: Another workarund could be to extend you class model by an additional class
PlayerInGame
:As you can see by the
Single
method in thePlayerBlack
andPlayerWhite
properties in theGame
class you have to make sure in your business logic to create the properPlayerInGame
entities so that yourPlayersInGame
collection always has two elements with Black or White flag respectively.我会这样解决这个问题:
I would tackle the problem like this: