appsecguy
appsecguy

Reputation: 1049

Entity Framework duplicate key issue

I have an entity called Users, and an en entity called Groups.

I have a few groups confined in my database already, but no users. I am trying to add users, and configure groups for them, but I receive the following error:

Violation of PRIMARY KEY constraint 'PK_dbo.Groups'. Cannot insert duplicate key in object 'dbo.Groups'. The duplicate key value is (admins). The statement has been terminated.

Entities are defined as follows (some info stripped)

public class User{
    [Key, Column(Order = 0)]
    public string Name {get;set;}
    [ForeignKey("Organization")]
    [Key, Column(Order = 1)]
    public string Organization {get;set;}
    public virtual Organization Org {get;set;}
    public virtual ICollection<Group> Groups {get;set;}
}

public class Group {
    [Key, Column(Order=0)]
    public string GroupName {get;set;}
}

Am i missing something basic here?

Code I am using to add users:

var user = new User 
{
    Name = "NAME", 
    Organization = "Organization Name", 
    Org = orgObject, 
    Groups = LIST OF GROUPS    // LIST OF GROUPS is an IList<Group> object
};
context.Users.Add(user);
context.SaveChanges();

Upvotes: 0

Views: 3360

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

My thought is that because the List was obtained elsewhere, rather than from the db context, it is trying to re-add it when it already exists. Would that be accurate?

Correct. You have to attach the items to current dbContext to make it work.

var user = new User 
{
    Name = "NAME", 
    Organization = "Organization Name", 
    Org = orgObject, 
    Groups = LIST OF GROUPS    // LIST OF GROUPS is an IList<Group> object
};

foreach(var group in LIST OF GROUPS)
    context.Groups.Attach(group);

context.Users.Add(user);
context.SaveChanges();

Upvotes: 1

Related Questions