I'm sure there is a very simple solution for this. Using EntityFramework, given these three models:
public class Player {
public string Id {get; set;}
public string Name {get; set;}
public Team Team {get; set;}
}
public class Team {
public string Id {get; set;}
public string Name {get; set;}
}
public class Sponsor {
public string Id {get; set;}
public Player Representative {get; set;}
}
And corresponding sets in the context:
public DbSet<Player> Players { get; set; }
public DbSet<Team> Teams { get; set; }
public DbSet<Sponsor> Sponsors { get; set; }
The problem comes when adding a new Player when the Team already exists.
Only adding a new Player works fine:
// player is a new Player
using (var db = new MyContext())
{
db.Players.AddOrUpdate(player);
db.SaveChanges();
}
But trying to change the Representative property on an existing Sponsor fails:
using (var db = new MyContext())
{
var sponsor = db.Sponsors.Single(s => s.Id == 1);
sponsor.Representative = player;
db.SaveChanges();
}
This fails with the error:
{"Violation of PRIMARY KEY constraint 'PK_dbo.Teams'. Cannot insert duplicate key in object 'dbo.Teams'."}
I don't want it to duplicate the Team entry.