将实体从一个上下文传输到另一个上下文时,AddObject 和 Attach 有什么不同
如果我首先使用数据库来构建上下文,然后实例化该上下文两次。我想从第一个上下文中查询特定实体并将其添加到第二个上下文中,使用 AddObject 和 Attach 之间有什么不同。 例如。
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Attach(stu);
它们之间有什么
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Students.AddObject(stu);
区别? 提前致谢!
If I have use database first to build a context, and instantiate this context twice. I want to query a specific entity from the first context and add it to the second context, what's the different between using AddObject and Attach.
eg.
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Attach(stu);
and
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Students.AddObject(stu);
What's the difference between them?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Attach 方法将附加对象或处于未更改状态的对象图。这意味着,如果您在附加对象后未对其进行任何修改,则当您调用
SaveChanges()
方法时,EF 将不会对该对象发出任何更新/删除命令。但是,当您使用
AddObject
方法时,EF 会将对象作为新实体插入到SaveChanges()
方法中。如果
context2
连接到不同的数据库并且您想要复制实例,则可以使用AddObject
。否则请使用Attach
方法。The Attach method will attach the object or object graph in Unchanged state. That means if you don't do any modifications to the object after you attach it, EF will not issue any Update/Delete commands for that object when you call
SaveChanges()
method.But when you use
AddObject
method EF will insert the object as a new entity inSaveChanges()
method.If the
context2
is connected to a different database and you want to copy the instance then you can useAddObject
. Otherwise use theAttach
method.