实体框架:附加相关对象和其他状态管理

发布于 2024-11-18 21:59:22 字数 517 浏览 8 评论 0原文

我有一个使用实体框架代码优先的应用程序。我正在尝试编写我的资源访问层。我有几个对象,它们都有单独的数据库表和很多对象关系。有人可以向我指出具有相关对象的 CRUD 方法的最新示例吗?我发现的所有内容都使用旧版本(我使用 DbContext,而不是 ObjectContext 等),并且我自己编写它时遇到问题。

例如,我当前正在处理一个与其自身具有父子关系的对象。我正在尝试编写 Create 方法。如果我使用 context.Objects.Add(newObject) ,那么所有子对象的状态也会更改为“已添加”,这意味着会添加重复的子对象。因此,我尝试循环遍历所有子项并将它们附加到上下文,但是之前不存在的任何子项都不会添加到数据库中,并且会引发 DbUpdateException 。

是否有一种通用方法可以附加所有相关实体并使其状态正确?您能给我的任何帮助将不胜感激。谢谢!

编辑:

我尝试使用 Load() 显式加载子项,然后添加初始对象。不幸的是,它引发了异常,因为父级注释在其子级列表中包含该子级,但现有子级的 ParentID 尚未更新。

I have an application which uses Entity Framework Code First. I am attempting to write my resource access layer. I have several objects which all have separate database tables and a lot of object relationships. Can someone point me to an up-to-date example of CRUD methods with related objects? Everything I have found uses an older version (I use DbContext, not ObjectContext, etc.) and I am having problems writing it myself.

For example, I am currently working on an object with a parent-child relationship with itself. I am attempting to write the Create method. If I use context.Objects.Add(newObject) then all the children objects also have their state changed to Added, which means that duplicate children are added. So I tried looping through all the children and attaching them to the context, but then any children that did not previously exist do not get added to the database and a DbUpdateException is thrown.

Is there a generic way I can attach all related entities and have their states be correct? Any help you can give me would be appreciated. Thanks!

Edit:

I tried explicitly loading the children using Load() and then adding the initial object. Unfortunately, it caused an exception because the parent comment had the child in its list of children but the parentID of the existing child had not yet been updated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

哥,最终变帅啦 2024-11-25 21:59:22

不,无法附加整个图并让 EF 自动设置正确的状态 - 这些问题自 ObjectContext API 以来没有改变。您必须始终为每个实体和关系手动设置状态,或者必须从附加实体构建图形。唯一的例外是自我跟踪实体,但是DbContext API 不支持它们。

No there is no way to attach whole graph and let EF automatically set correct state - these problems didn't changed since ObjectContext API. You must always set state manually for each entity and relation or you must build the graph from attached entities. The only exception are Self tracking entities but they are not supported with DbContext API.

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