0

I am creating a junction table between Identity User and a Game table. This table is called UserGame and has two foreign keys (UserID, GameID) and one additional field to store the score.

public class UserGame
{
    [Key]
    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public int GameID { get; set; }
    public virtual Game Game { get; set; }

    public int Score { get; set; }
}

My confusion lies with creating a new UserGame record. How would I go about doing this and is my approach correct?

Update (This worked):

 [HttpPost]
    public ActionResult SubmitScore(int gameID, int score)
    {
        var playerRecord = new UserGame();

        playerRecord.ApplicationUserID = User.Identity.GetUserId();
        playerRecord.GameID = gameID;
        playerRecord.Score = score;

        return Json(new { success = true });
    }
Gareth Quirke
  • 216
  • 1
  • 8
  • 25

2 Answers2

1

Example of configuring many-to-many relationship in entity framework

Examle of inserting related objects

A couple of tips: I wouldn't declare a primary key in the junction entity as junctions are usually defined by composite keys. Keep in mind that dbcontext.SaveChanges() will look for child entities and save those as well.

Community
  • 1
  • 1
NathanS
  • 61
  • 3
  • 2
    Thanks for your answer, my issue with that example is storing the additional field 'Score'. Should this be in the Game class? – Gareth Quirke Feb 28 '17 at 21:36
1

Both ApplicationUserId and GameId must have a [Key, Column(Order = 0)] attribute. Just set the first to Order 0 and the other to 1.

public class UserGame
{
    [Key, Column(Order = 0)]
    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    [Key, Colum(Order = 1)]
    public int GameID { get; set; }
    public virtual Game Game { get; set; }

    public int Score { get; set; }
}

Then you have the choice to add new record, go through nav property from Game or ApplicationUser or directly with your UserGame class.

dbraillon
  • 1,742
  • 2
  • 22
  • 34
  • 2
    Thanks for the help! Still a little lost on adding a new record. I have chosen to go directly with my UserGame class. I created a new UserGame object in my controller. I can assign the gameID and score. I'm wondering if this approach is correct: Retrieve the current user signed in through the User.Identity.GetUserID() and set this as the ApplicationuserID field. – Gareth Quirke Feb 28 '17 at 23:19
  • Yup, this is a way to go, to add the newly UserGame entity, add it to your context. You should have it as DbSet in your DbContext right ? – dbraillon Mar 01 '17 at 06:36
  • 2
    It's working now, could not find this approach anywhere. thanks alot – Gareth Quirke Mar 01 '17 at 12:48