I am creating a system that can register players playing games. One game can have up to 4 players, and players can have unlimited games. The relevant source code for this:
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Username { get; set; }
public virtual ICollection<Game> Games { get; set; }
}
And:
public class Game
{
public int GameId { get; set; }
[Required]
public string Location { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
EF generated the tables properly and also one extra table: PlayerGames, which has two columns: Player_PlayerId and Game_GameId. It looks like this: https://i.stack.imgur.com/mVgm9.jpg
The Create method of the GamesController looks like this:
public ActionResult Create([Bind(Include = "GameId,Location,PlayerId")] Game game)
{
int[] ids = Request.Form["PlayerId"].Split(',').Select(Int32.Parse).ToArray();
List<Player> k = ids.Select(t => db.Players.First(x => x.PlayerId == t)).ToList();
ICollection<Player> players = ids.Select(t => db.Players.First(x => x.PlayerId == t)).ToList();
game.Players = players;
db.Database.Log = s => Debug.Write(s);
if (ModelState.IsValid)
{
db.Games.Add(game);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(game);
}
The problem is that db.SaveChanges() generates a Query that ignores the order of the Players list: the Id-s will be in order every single time. However, for the system it is important to know what order the players are in the list. Is there any way I could insert it into the database preserving the order?
Here is the SQL log for reference:
INSERT [dbo].[PlayerGames]([Player_PlayerId], [Game_GameId])
VALUES (@0, @1)
-- @0: '2' (Type = Int32)
-- @1: '1013' (Type = Int32)
-- Executing at 4/21/2015 1:22:13 PM +02:00
-- Completed in 1 ms with result: 1
INSERT [dbo].[PlayerGames]([Player_PlayerId], [Game_GameId])
VALUES (@0, @1)
-- @0: '3' (Type = Int32)
-- @1: '1013' (Type = Int32)
-- Executing at 4/21/2015 1:22:13 PM +02:00
-- Completed in 0 ms with result: 1
INSERT [dbo].[PlayerGames]([Player_PlayerId], [Game_GameId])
VALUES (@0, @1)
-- @0: '4' (Type = Int32)
-- @1: '1013' (Type = Int32)
-- Executing at 4/21/2015 1:22:13 PM +02:00
-- Completed in 0 ms with result: 1
INSERT [dbo].[PlayerGames]([Player_PlayerId], [Game_GameId])
VALUES (@0, @1)
-- @0: '6' (Type = Int32)
-- @1: '1013' (Type = Int32)
-- Executing at 4/21/2015 1:22:13 PM +02:00
-- Completed in 0 ms with result: 1