KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have an entity with a foreign key relationship to an asp.net membership provider users table. This portion of the model looks like this: I can't seem to assign the foreign key relationship when inserting the Users table record, the record containing the foreign key to the aspnet_Users table. I keep getting the error: An item with the same key has already been added. The code I'm using looks like: UserAdmin userToAdd = new UserAdmin(); ... userToAdd.aspnet_Users = membershipUser; //line above OR line below userToAdd.aspnet_UsersReference.EntityKey = new System.Data.EntityKey("ProjectEntities.aspnet_Users", "UserId", membershipUser.UserId); db.AddToUsers(userToAdd); db.SaveChanges(); Is the issue that I'm asking the EF to add a new aspnet_Users table record (the record for the associated primary key table) when that record is already there? How would I assign a foreign key value to an entity where the primary key record already exists? Updated test code block: MembershipUser membershipUser = Membership.CreateUser("blah@blah.com", "pass", "blah@blah.com"); Entities db = new Entities(); UserAdmin newUser = new UserAdmin(); newUser.Name = "blah"; newUser.DateAdded = DateTime.Now; Guid key = new Guid(membershipUser.ProviderUserKey.ToString()); aspnet_Users membershipUserRecord = db.aspnet_Users.Where(u => u.UserId == key).FirstOrDefault(); newUser.aspnet_Users = membershipUserRecord; //newUser.aspnet_UsersReference.EntityKey = new System.Data.EntityKey("Entities.aspnet_Users", "UserId", membershipUserRecord.UserId); db.ObjectStateManager.ChangeObjectState(membershipUserRecord, EntityState.Unchanged); db.AddToUsers(newUser); db.SaveChanges(); This code generates the error: An item with the same key has
Tags (comma-separated)
Save Edits
Cancel