0

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(); 
7
  • 2
    Show the code you're using for adding users. Commented Oct 6, 2015 at 23:41
  • Hm, thought I did, guess it didn't save. Editing now :) Commented Oct 6, 2015 at 23:42
  • @appsecguy, you did have the code. When voytek edited your post he removed that part of the question. Not sure why that edit was approved. Commented Oct 6, 2015 at 23:43
  • My thought is that because the List<Group> was obtained elsewhere, rather than from the db context, it is trying to re-add it when it already exists. Would that be accurate? Commented Oct 6, 2015 at 23:47
  • 1
    @appsecguy: You're correct as to the reason why it's happening. I'm trying to figure out how to fix the problem. I think part of the problem is a fundamental issue with the model. It seems like you have a many-to-many (a group can have many users and a user can belong to many groups) but the model doesn't really reflect that. And using the group name as the primary key for groups isn't a great idea either. Commented Oct 6, 2015 at 23:49

1 Answer 1

1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.