.net 实体框架 - 已添加具有相同键的项目。- 尝试定义外键关系时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3594236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:39:35  来源:igfitidea点击:

Entity Framework - An item with the same key has already been added. - Error when trying to define foreign key relationship

.netlinqentity-frameworklinq-to-entitiesentity-framework-4

提问by BrooklynDev

I have an entity with a foreign key relationship to an asp.net membership provider users table.

我有一个与 asp.net 成员资格提供程序用户表具有外键关系的实体。

This portion of the model looks like this:

模型的这一部分如下所示:

alt text

替代文字

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_Userstable. I keep getting the error:

插入用户表记录时,我似乎无法分配外键关系,该记录包含aspnet_Users表的外键。我不断收到错误:

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_Userstable record (the record for the associated primary key table) when that record is already there?

aspnet_Users当该记录已经存在时,我要求 EF 添加新表记录(关联主键表的记录)的问题是什么?

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("[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();

This code generates the error:

此代码生成错误:

An item with the same key has already been added.

已添加具有相同键的项目。

回答by BrooklynDev

OK I figured this one out. As usual it was just me making a mistake and not catching it right away because I was looking in the wrong place.

好的,我想通了这一点。像往常一样,只是我犯了一个错误并没有立即抓住它,因为我看错了地方。

The issue was due to my table inheritance and the configuration at the database level. I had the child table's (UserAdmin) foreign key field defined as an identity, which then showed up in my model as StoreGeneratedPattern = Identity. This was causing the 'An item with the same key has already been added error' when EF was trying to propagate the parent's primary key to it's child's foreign key field.

问题是由于我的表继承和数据库级别的配置造成的。我将子表的 (UserAdmin) 外键字段定义为身份,然后在我的模型中显示为 StoreGeneratedPattern = Identity。当 EF 尝试将父项的主键传播到其子项的外键字段时,这会导致“已添加具有相同键的项目错误”。

Once I removed the identity specification from the UserAdmins table the issue went away.

一旦我从 UserAdmins 表中删除了身份规范,问题就消失了。

Problem solved.

问题解决了。

回答by Ladislav Mrnka

Yes that is exactly the problem. How did you get membershipUser entity? If you didn't get it from current ObjectContext EF thinks that it is the new one and it tries to insert it to aspnet_users table.

是的,这正是问题所在。你是如何获得membershipUser实体的?如果您没有从当前的 ObjectContext 中获取它,EF 会认为它是新的,并尝试将其插入到 aspnet_users 表中。

Try to use this code after adding user to ObjectSet:

在将用户添加到 ObjectSet 后尝试使用此代码:

// db is ObjectContext instance
db.ObjectStateManager.ChangeObjectState(membershipUser, EntityState.Unchanged);

Therea are probably some other ways how to achieve same result but this works for me.

可能还有其他一些方法可以实现相同的结果,但这对我有用。