3

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.

user888734
  • 3,797
  • 5
  • 36
  • 67
  • Possible duplicate of [Entity Framework disconnected graph and navigation property](http://stackoverflow.com/questions/25026542/entity-framework-disconnected-graph-and-navigation-property) – mahdi mahzouni Jan 18 '16 at 11:12

2 Answers2

4

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
0

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.

Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62