我有一個具有與asp.net成員資格提供程序用戶表的外鍵關係的實體。實體框架 - 已添加具有相同密鑰的項目。 - 嘗試定義外鍵關係時出錯
模型的這一部分看起來是這樣的:
我似乎無法插入用戶表記錄,包含外鍵aspnet_Users
表中的記錄時指定的外鍵關係。我不斷收到錯誤:
An item with the same key has already been added.
我使用看起來像代碼:
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();
是,我問EF添加新的aspnet_Users
表記錄(記錄的問題關聯的主鍵表)何時該記錄已經存在?
如何將外鍵值分配給主鍵記錄已存在的實體?
更新測試代碼塊:
MembershipUser membershipUser = Membership.CreateUser("[email protected]", "pass", "[email protected]");
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();
此代碼生成錯誤:
An item with the same key has already been added.
MembershipUser是由(相同的)DataContext跟蹤的嗎? – 2010-08-29 10:06:26
是的membershipUser記錄是由與用於提交新用戶記錄相同的實體模型實例檢索的。 – BrooklynDev 2010-08-29 11:25:44