如何添加没有相关实体但保存关系的实体?

How to add an entity without related entities, but saving relation?

据我了解,如果我在这样的上下文中更改条目的状态:

context.Entry(doc).State = EntityState.Added;

doc 后面的整个对象图将设置为 EntityState.Added。这就是这种机制描述的方式 here:

Note that for all of these examples if the entity being added has references to other entities that are not yet tracked then these new entities will also be added to the context and will be inserted into the database the next time that SaveChanges is called.

在我的情况下,这种行为是不可取的。当我收到 doc 实体时,它的关系已经在数据库中(在不同的上下文中添加)并且再次添加它们会导致错误。我需要将 doc 添加到包含所有引用的数据库中,但不要尝试在图形中添加其他对象。

当然,我可以遍历所有图形并显式设置状态,但是是否存在更简单的方法?

你可以看看 GraphDiff

根据这个dedicated blog entry,它似乎符合您的需求:

Say you have a Company which has many Contacts. A contact is not defined on its own and is a One-To-Many (with required parent) record of a Company. i.e. The company is the Aggregate Root. Assume you have a detached Company graph with its Contacts attached and want to reflect the state of this graph in the database.

At present using the Entity Framework you will need to perform the updates of the contacts manually, check if each contact is new and add, check if updated and edit, check if removed then delete it from the database. Once you have to do this for a few different aggregates in a large system you start to realize there must be a better, more generic way.

Well good news is that after a few refactorings I've found a nice solution to this problem.

Entity Framework Core 中,行为发生了变化,调用:

context.Entry(asset).State = EntityState.Added;

只会影响实体,不会影响相关实体。

我知道问题是针对 Entity Framework classic(不是 Core),但肯定会有更多人使用 EF Core 到达这里(像我一样)