【问题标题】:When the EntityKey create and when it disposedEntityKey 的创建时间和处置时间
【发布时间】:2011-12-16 07:52:32
【问题描述】:

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

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仍然存在?

有人可以帮忙吗?提前致谢!

【问题讨论】:

    标签: entity-framework detach entitykey


    【解决方案1】:

    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
    

    【讨论】:

    • 非常酷!感谢您对 EntityKey 的描述!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-11-30
      • 2011-03-30
      • 2021-05-03
      • 1970-01-01
      • 2013-06-20
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多