EF4 是否始终对新添加的实体使用临时密钥?
我一直在尝试使用 TryGetObjectByKey 在上下文中查找新添加的实体:
Dim ObjectFound As Boolean = Context.TryGetObjectByKey(entityKey, obj)
我发现 TryGetObjectByKey 总是失败,即使我知道我正在查找的实体已添加到上下文中。有问题的实体使用电子邮件地址作为主键,并且该电子邮件地址是通过实体的构造函数提供的(它不是由数据库生成的):
Public Class Customer
Private _email as string
Public Sub New (Email as string)
'Email is the primary key in the DB and the entity key in EF4.
'It is not generated by the DB.
_email = Email
End Sub
End Class
经过进一步调查,我发现所有添加的实体的 EntityKeys 都没有值,并且它们的 IsTemporary 标志设置为 true。 TryGetObjectByKey 失败,因为尚未设置所添加对象的 EntityKey。
我最初的印象是,如果 EntityKey 不是由数据库生成的,那么 EntityKey 将在调用 AddObject 时立即生成。因此,有两个问题:
1)我是否应该期望所有新添加的实体都具有临时 EntityKey?
2)如果#1为真,我如何通过主键找到新添加的实体?
I have been trying to find newly added entities on a context by using TryGetObjectByKey:
Dim ObjectFound As Boolean = Context.TryGetObjectByKey(entityKey, obj)
I found that TryGetObjectByKey always failed, even when I knew that the entity I was looking for had been added to the context. The entity in question uses email address as the primary key, and that email address is provided through the constructor for the entity (it is not generated by the DB):
Public Class Customer
Private _email as string
Public Sub New (Email as string)
'Email is the primary key in the DB and the entity key in EF4.
'It is not generated by the DB.
_email = Email
End Sub
End Class
After further investigation I found that the EntityKeys for all of the added entities had no values, and their IsTemporary flag was set to true. TryGetObjectByKey was failing because the EntityKey for the added objects was not yet set.
I was originally under the impression that the EntityKey would be generated immediately upon calling AddObject if the EntityKey was not generated by the DB. So, two questions:
1) Should I expect all newly added entities to have temporary EntityKeys?
2) If #1 is true, how can I find newly added entities by primary key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
<一href="http://www.google.nl/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCYQFjAA&url=http:// /msdn.microsoft.com/en-us/library/dd283139.aspx&ei=oqcqT7L_PJGc-wa6sfSDDg&usg=AFQjCNFz7Us6MgzwEG48Vy8GuaGzPJQTjw" rel="nofollow">MSDN 声明如下:
仅在 SaveChanges(以及相应的 Insert 语句)之后才会创建 EntityKey。
MSDN states the following:
Only after SaveChanges (and the corresponding Insert statement) an EntityKey is created.