Reputation: 3897
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.
Upvotes: 3
Views: 2055
Reputation: 109119
This is due to a known bug in AddOrUpdate
. A work-around is to replace the player
reference to the object that is actually tracked by EF:
using (var db = new MyContext())
{
db.Players.AddOrUpdate(player);
db.SaveChanges();
// Get the actually tracked player:
player = db.Players.Local.Single(p => p.Id == player.Id);
}
In your current code, when you do ...
sponsor.Representative = player;
... EF "thinks" you're adding a new player because it doesn't track the object player
is referring to.
Upvotes: 4
Reputation: 3034
As we can see in your error you are trying to add multiple Teams object with the same ID that way you are getting this error, make primary key auto increment your problem will be solved.
Upvotes: 0