问题描述
我有一个大的图形的实体,我以不连贯的方式工作。它们是POCO实体,实现我自己的简单更改跟踪标志(IsNew,IsChanged,IsDeleted)。当保存更改的时候,我将整个图形传回业务层,它执行以下操作: - 上下文.Batches.Attach(批次);
其中批处理
图层的顶部。这具有级联效应,并附加图中的所有实体,这些都处于不变的状态。然后,我根据我的更改跟踪标志的值,通过 ObjectStateManager
逐个层次结构设置每个实体的状态。
这种方法的问题是新实体需要分配唯一的ID(尽管是身份列)。我不能将它们全部保留为0,否则 Attach
失败,并显示消息具有相同密钥的对象已存在...。
不必分配临时的,唯一的ID开始有点凌乱,我想知道是否有更好的解决方案。我想知道我是否可以走图,做一个附加
或一个添加
>一个实体一次(根据我的更改跟踪标志),但这似乎是不可能的,因为两种方法级联,导致所有的子实体被添加或附加。有没有办法?
我使用的是EF5,ObjectContext模板,如果这有所作为。
首先从上下文中获取当前实体图(更改跟踪
和启用代理生成
),然后根据分离的图形(使用您自己的内部持久性状态字段),走每个节点并更新/删除/添加数据。
I have a large "graph" of entities that I work with in a disconnected fashion. They are POCO entities, implementing my own simple change tracking flags (IsNew, IsChanged, IsDeleted). When the time comes to save changes, I pass the entire graph back to the business tier, which does the following:-
context.Batches.Attach(batch);
where batch
is the entity at the very top of the graph hierarchy. This has a "cascading effect" and attaches all entities in the graph, which all end up in an unchanged state. I then walk through the hierarchy setting each entity's state via the ObjectStateManager
, based on the values of my change tracking flags.
The problem with this approach is that new entities need to be assigned unique IDs (despite being "identity" columns). I can't just leave them all as 0 otherwise the Attach
fails with the message "An object with the same key already exists...".
Having to assign temporary, unique IDs is starting to get a bit messy, and I wondered if there was a better solution. I wondered if I could walk the graph and do an Attach
or an Add
one entity at a time (based on my change tracking flags), but this doesn't seem to be possible, as both methods "cascade", resulting in all child entities getting added or attached too. Is there any way around this?
I'm using EF5, ObjectContext template, if that makes a difference.
It would be much easier to first fetch the current entity graph from the context (with Change Tracking
and Proxy Generation
enabled), then walk each node and update/delete/add data based on the detached graph (using your own internal persistence status field).
这篇关于实体框架 - 更新实体的大图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!