I am making a logging program that logs stats from a game. i have a db with unique Players. Upon a new game i load the players and associate them with a dataset of the type PlayerData which i save to the db at the end of the round.
My problem is, that when i save MatchData which contains references to the already exixting players in db, i save the same players again to the db and therefore duplicate them. (which i bad!)
Can't entity framework just save a reference to the player already in the database? Ane if, how? if not, do you guys have a walkaround to this issue?
MatchData class holds data for a specific match:
public class MatchData
{
[Key]
public int Id { get; set; }
private List<PlayerData> blueTeam = new List<PlayerData>();
private List<PlayerData> redTeam = new List<PlayerData>();
//other relevant data
}
PlayerData class holds data for a specific player in a match:
public class PlayerData
{
[Key]
public int Id { get; set; }
public Player Player { get; set; }
//other relevant data
}
Player class holds the data for a specific player for life (stats, name, email, etc):
public class Player
{
[Key]
private int id; // full props
private string name; // full props
private string email; // full props
//other relevant data
}
DBContext:
class DBBooneContext : DbContext
{
public DbSet<Player> Player { get; set; }
public DbSet<PlayerData> PlayerData { get; set; }
public DbSet<MatchData> MatchData { get; set; }
}
And here is how i save the matchData to db.
public static void SaveMatchData(MatchData matchData)
{
using (DBBooneContext db = new DBBooneContext())
{
db.MatchData.Add(matchData);
db.SaveChanges();
}
}