Dane Looman
Dane Looman

Reputation: 89

Entity Framework Core - Unique Constraint

I have two models (User and Game) They are connected by another model named PlayerID. For Instance a user can have an special ID for each game. I would like to set it to that a user can only have one ID for each game. 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. So MTG has DCI numbers and so on. 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.

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

    public string GamePlayerID { get; set; }

    public User User { get; set; }

    public Game Game { get; set; }

}

Upvotes: 3

Views: 1798

Answers (1)

Silvermind
Silvermind

Reputation: 5944

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);
}

Upvotes: 5

Related Questions