我创建了一个新对象,并希望将其附加到类似下面的上下文中,
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类,但还是看不清楚。何时创建EntityKey并将其附加到对象?我在哪里可以找到它?如果我分离对象,为什么EntityKey仍然存在?
有人能帮上忙吗?提前感谢!
发布于 2011-12-16 16:13:03
EntityKey是一个对象,实体框架使用它唯一地标识您的对象并跟踪它。
在构造新对象时,实体的关键属性是null (或0)。ObjectContext不知道你的实体是否存在,也不会跟踪它,所以没有实体键。
当您将对象添加到上下文中时,将构造一个临时键。之后,您可以将更改保存到数据库中。这将生成一条Insert语句,并从数据库中检索新的键,构造永久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-16 16:14:58
可以将EntityKey类看作是实体的惟一标识符。Context将其用于各种操作,如更改跟踪、合并选项等。如果您不想为新对象指定entitykey,请使用context.AttachTo("Users",user),context将为您生成entitykey。
https://stackoverflow.com/questions/8531297
复制相似问题