Entity Framework Core - Unique Constraint

asp.net-core c# entity-framework-core model-view-controller

Question

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

}

1
2
11/16/2018 6:53:13 PM

Accepted Answer

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);
}
3
11/16/2018 7:06:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow