将实体从一个上下文传输到另一个上下文时,AddObject 和 Attach 有什么不同

发布于 2024-12-21 01:23:03 字数 368 浏览 2 评论 0原文

如果我首先使用数据库来构建上下文,然后实例化该上下文两次。我想从第一个上下文中查询特定实体并将其添加到第二个上下文中,使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2024-12-28 01:23:03

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 in SaveChanges() method.

If the context2 is connected to a different database and you want to copy the instance then you can use AddObject. Otherwise use the Attach method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文