0

我创建了一个新对象并希望将其附加到这样的上下文中,

User user = new User();
user.userName=”Kobe”;
context.Attach(user);

出现一条错误消息——“无法将具有空 EntityKey 值的对象附加到对象上下文”。如果我从数据库中查询出一个用户对象并将其 EntityKey 分配给新对象,然后像这样分离查询结果对象,

User user = (from u in context.Users where u.userID == 1 select u).First();
User newUser = new User();
newUser.userName = “Kobe”;
newUser.EntityKey = user.EntityKey;
context.Detach(user);
context.Attach(newUser);

出现另一条错误消息 - “无法附加对象,因为作为 EntityKey 一部分的属性的值与 EntityKey 中的相应值不匹配。” 我真的不知道EntityKey是什么,我在网上搜索并在MSDN中看到了EntityKey Class,但仍然无法理解。当 EntityKey 创建并附加到对象时?我在哪里可以找到它?如果我分离对象,为什么 EntityKey 仍然存在?

任何人都可以帮忙吗?提前致谢!

4

2 回答 2

3

AnEntityKey是实体框架用来唯一标识您的对象并跟踪它的对象。

当您构造一个新对象时,您的实体的关键属性是null(或0)。ObjectContext不知道您是实体存在并且尚未跟踪它,因此没有实体键。

当您将对象添加到上下文时,会构造一个临时键。之后,您可以将更改保存到数据库。这将生成一个插入语句并从数据库中检索新密钥,构造永久密钥EntityKey并更新它对临时密钥的所有引用。

附加是另一回事。当对象已存在于数据库中但与 ObjectContext 没有连接时,您将实体附加到 ObjectContext。

因此,在您的情况下,您应该更改代码以将新实体添加到:

User user = new User();
user.userName=”Kobe”;

context.Users.Add(user); // Generate a temporary EntityKey
// Insert other objects or make changes
context.SaveChanges(); // Generate an insert statement and update the EntityKey
于 2011-12-16T08:13:03.370 回答
0

将 EntityKey 类视为实体的唯一标识符。Context 将它用于各种操作,例如更改跟踪、合并选项等。如果您不想为新对象指定 entitykey,请使用 context.AttachTo("Users",user) 和 context 将为您生成 entitykey。

于 2011-12-16T08:14:58.397 回答