首页 > 解决方案 > 如何设置多对多关系,实体的不同关系状态可能会有所不同

问题描述

我有两个实体 Player 和 Game 是多对多的关系。我正在使用 EF core 2.1 开发我的应用程序,因此我必须设置中间类并使用流利的 api 对其进行配置。我想为每场比赛提供选项,每个球员都可以决定他是否会参加比赛、不参加比赛或者他还没有决定。最后,我想显示关于每场比赛的信息,其中包含三个由玩家组成的列表,基于他们的“你在玩吗?” 选择。而且我不确定我应该如何将这些信息存储在数据库中

玩家等级

public class Player
{
    public Player()
    {
        this.PlayerGames = new HashSet<PlayerGame>();
    }

    public long Id { get; set; }
    public virtual ICollection<PlayerGame> PlayerGames { get; set; }
    .....
}

游戏课

public class Game
{
    public Game()
    {
        this.PlayerGame = new HashSet<PlayerGame>();
    }
    public long Id { get; set; }
    public virtual ICollection<PlayerGame> PlayerGames { get; set; }
}

玩家游戏类

public class PlayerGame
{
    public long PlayerId { get; set; }
    public Player Player { get; set; }
    public long GameId { get; set; }
    public Game Game { get; set; }
}

我想出了一个想法,我可以在 PlayerGame 中间表中添加一列并将此信息存储在那里。例如,玩家约翰将参加比赛 A 和 B,但他不会参加比赛 C。

所以中间表看起来像:

_____________________________________
|PlayerId |GameId  | PlayerStatus    |
-------------------------------------
|JohnId   |GameAId | 1               |         1 - will play
|JohnId   |GameBId | 1               |         2 - won't play
|JohnId   |GameCId | 2               |         3 - not decided

这个想法看起来不错还是你有更好的选择?

标签: c#.net-coreentity-framework-core

解决方案


对于您正在寻找的内容,并且为了简单起见,您选择的PlayerStatus将正常工作。根据您使用的数据库,您可以利用该表列的不同数据类型来更无缝地与 EF 配合使用。

例如,在 SQL Server 中,您可以使用bit数据类型并将其设为可为空,这样您的 EF 模型中的 null 就可以简单地使用bool?

public class PlayerGame
{
    public bool? PlayerStatus { get; set; }
}

潜在值如下所示:1 - 将播放,0 - 不会播放,null - 未决定

高温高压


推荐阅读