简体   繁体   English

实体框架核心-唯一约束

[英]Entity Framework Core - Unique Constraint

I have two models (User and Game) They are connected by another model named PlayerID. 我有两个模型(用户模型和游戏模型),它们通过另一个名为PlayerID的模型连接。 For Instance a user can have an special ID for each game. 例如,用户可以为每个游戏拥有一个特殊的ID。 I would like to set it to that a user can only have one ID for each game. 我想将其设置为每个游戏用户只能拥有一个ID。 What is the best practice for that? 最佳做法是什么?

EDIT: 编辑:

I will expand it further so you know exactly what I am building. 我将进一步扩展它,以便您确切地知道我在构建什么。 I have players who play games such as Magic the Gathering or Pokemon etc. Each of those games assigns their players IDs. 我有一些玩过《 Magic the Gathering》或《 Pokemon》等游戏的玩家。每个游戏都为其分配玩家ID。 So MTG has DCI numbers and so on. 因此MTG具有DCI编号等等。 Each player will have an ID for each Game but not more than one per game and I need to make sure that players can't have multiple IDs for the same game. 每个玩家将为每个游戏拥有一个ID,但每个游戏不得超过一个ID,我需要确保玩家不能为同一游戏拥有多个ID。

public class PlayerID
{
    public int PlayerID { get; set; }

    public string GamePlayerID { get; set; }

    public User User { get; set; }

    public Game Game { get; set; }

} }

A player can join multiple games, but cannot join the same game more than once. 玩家可以加入多个游戏,但不能多次加入同一游戏。

That also belongs in your business logic, but you can define a constraint to safe-guard yourself from mistakes. 这也属于您的业务逻辑,但是您可以定义约束以保护自己免受错误的侵害。

You need a many-to-many relationship in your logic: 您的逻辑中需要多对多关系:

public class Game
{
    public int Id { get; set; }

    public ICollection<GamePlayer> GamePlayers { get; set; }
}

public class Player
{
    public int Id { get; set; }

    public ICollection<GamePlayer> GamePlayers { get; set; }
}

public class GamePlayer
{
    public int GameId { get; set; }
    public Game Game { get; set; }
    public int PlayerId { get; set; }
    public Player Player { get; set; }
}

...

modelBuilder.Entity<GamePlayer>(e =>
{
    // This safe-guards for duplicates.
    e.HasIndex(prp => new { prp.GameId, prp.PlayerId }).IsUnique();
    e.HasOne(prp => prp.Game).WithMany(prp => prp.GamePlayers).HasForeignKey(prp => prp.GameId);
    e.HasOne(prp => prp.Player).WithMany(prp => prp.GamePlayers).HasForeignKey(prp => prp.PlayerId);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM