Skip to content

Change default graph behavior of Add/Attach/etc #4424

Closed

Description

@rowanmiller

In EF6.x the default behavior of these methods was to start tracking every reachable entity in the state being requested for the root entity. This caused a lot of issues because:

  1. Attaching a root would often end in exceptions because there were new entities in the graph (with no PK set) which would attempt to be tracked as unchanged, resulting in duplicate PK values.
  2. There was no easy mechanism to traverse over a graph and chose the state of each entity as you go.
  3. There was no ability to leave parts of the graph un-tracked (i.e. I want to add an order and I don't care about telling you the state of the Customer).

In EF Core we tried to alleviate some of these issues by initially making Add/Attach/etc. just work on a single object, but this caused a lot of confusion since it seems the natural expectation (based on the feedback we saw) is that you could add an Order and the OrderLines would be automatically added too.

We then tried an "Include Dependents" approach, where if you add a parent, we also include the children as added. This works well for some cases... but it gets pretty confusing. This is compounded by the fact that it's not always clear from your model which is the principal/dependent of a relationship.

After discussion, we realized that with some small variations on the rules from EF6.x, we already have APIs in EF Core to enable these scenarios:

There was no easy mechanism to traverse over a graph and chose the state of each entity as you go.

We have the TrackGraph API for exactly this purpose.

There was no ability to leave parts of the graph un-tracked (i.e. I want to add an order and I don't care about telling you the state of the Customer).

This is now supported in EF Core, our stack is capable of handling entities in the graph that it is not tracking. We have the DbContext.Entry(...).State API that allows you to put a single entity into the context without any graph behavior (i.e. no related entities are brought in).

Attaching a root would often end in exceptions because there were new entities in the graph (with no PK set) which would attempt to be tracked as unchanged, resulting in duplicate PK values.

We will adjust the graph behavior of these APIs as follows:

  • Add: Adds every reachable entity that is not already tracked
  • Attach: Attaches every reachable entity, except where a reachable entity has a store generated key and no key value is assigned, these will be marked as added.
  • Update: Same as Attach, but entities are marked as modified
  • Remove: Same as Attach, and then mark the root as deleted. Since cascade delete now happens on SaveChanges, this allows cascade rules to flow to entities later on.

Some important results of this behavior:

  • It works as expected for attached scenarios (i.e. non N-Tier scenarios). I.e. if I create a graph of objects and then call Add, they all get added.
  • For N-Tier scenarios, it leaves you with the ability to cycle over each entity and tell EF the state (which was blocked in EF6.x because you would get duplicate key exceptions). Of course, TrackGraph may also be a better API for these scenarios too.

Activity

  1. added this to the milestone on Jan 28, 2016
  2. ajcvickers commented on Jan 28, 2016

    @ajcvickers
    Contributor

    Nice write up. :-)

  3. julielerman commented on Feb 1, 2016

    @julielerman

    :(

    Thought I should clarify that ... :) .... sorry you weren't able to work it out. I liked that idea but also know that people are going to have a hard time with changed behavior no matter how many times you tell them "it's not EF6". I'm glad we still have ENTRY to add just the root. It was always a hard problem not being able to tear apart graphs for this purpose so that's still a big win. Agree re great detailed writeup. Thanks. Even Frans said "Tho, reading about the defaults, what they've picked is the best choice for POCOs I think." But he also adds "Root cause is lack of self tracking." (Don't ever bring that back! :) )

  4. tonysneed commented on Feb 1, 2016

    @tonysneed

    So just to clarify, we'll still be able to set an entity state to Added via TrackGraph and EF will only set the state of that single entity to Added?

  5. rowanmiller commented on Feb 1, 2016

    @rowanmiller
    ContributorAuthor

    @tonysneed if you want to set the state of a single entity then context.Entry(myEntity).State = EntityState.Added is probably the easiest. TrackGraph will work... but that is really designed for iterating over a graph of entities and setting the state for each one.

  6. tonysneed commented on Feb 1, 2016

    @tonysneed

    Thanks @rowanmiller, so context.Entry(myEntity).State = EntityState.Added will not set child entity states to Added, as it did in EF6. Just wanted to confirm, thanks!

  7. rowanmiller commented on Feb 1, 2016

    @rowanmiller
    ContributorAuthor

    @tonysneed correct, EF Core is now ok with having tracked entities reference entities that are not tracked.

  8. tonysneed commented on Feb 2, 2016

    @tonysneed

    Excellent. In case anyone is interested, Here is a test which shows the difference between EF 6 and EF Core when it comes to setting entity state to Added on a disconnected graph.

    [Fact]
    public void Set_state_should_mark_single_entity()
    {
        // Arrange
        var detail = new OrderDetail();
        var order = new Order
        {
            OrderDetails = new List<OrderDetail> { detail }
        };
    
        // Act: Set parent state to Added
        _context.Entry(order).State = EntityState.Added;
    
        // Assert for EF 6: Child state set to Added
        Assert.Equal(EntityState.Added, _context.Entry(detail).State);
    
        // Assert for EF Core: Child state remains Detached
        Assert.Equal(EntityState.Detached, _context.Entry(detail).State);
    }

    Here is the full source code for the tests.

  9. julielerman commented on Feb 2, 2016

    @julielerman
  10. rowanmiller commented on Feb 2, 2016

    @rowanmiller
    ContributorAuthor

    @julielerman and rename your repo to EFCore 😉

    BTW our nightly builds are pretty unstable at the moment due to moving over to .NET CLI... so you may want to hold off a couple of weeks.

  11. 19 remaining items

  12. divega commented on Jun 2, 2016

    @divega
    Contributor

    and sadly they use 0 as a valid key value for all kinds of tables

    If zero is a valid key you can change the type of the key to be nullable, e.g. int? instead of int. Then IsKeySet will return true for zero and false for null.

    So I am passing this root object to track changes. It is NOT iterating over any of the referenced objects or any of the child object lists.
    The relationships ARE spelled out in the fluent config.
    Do I need to use virtual for this to work?

    Not sure what the problem could be. You don't need to make the navigation properties virtual, in fact virtual doesn't make any difference with EF Core. Could you please create a new issue with a self-contained repro of this issue?

  13. johnkwaters commented on Jun 2, 2016

    @johnkwaters

    But then wouldn't I need a nullable pk in the db?

    Sent from my iPhone

    On Jun 2, 2016, at 2:23 PM, Diego Vega [email protected] wrote:

    and sadly they use 0 as a valid key value for all kinds of tables

    If zero is a valid key you can change the type of the key to be nullable, e.g. int? instead of int. Then IsKeySet will return true for zero and false for null.

    So I am passing this root object to track changes. It is NOT iterating over any of the referenced objects or any of the child object lists.
    The relationships ARE spelled out in the fluent config.
    Do I need to use virtual for this to work?

    Not sure what the problem could be. You don't need to make the navigation properties virtual, in fact virtual doesn't make any difference with EF Core. Could you please create a new issue with a self-contained repro of this issue?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub, or mute the thread.

  14. divega commented on Jun 2, 2016

    @divega
    Contributor

    No. The column will still be non-nullable as null is not a valid key value in a persisted object. It only means that the key can have a null value temporarily while it is in memory and before it is added to a DbContext.

  15. julielerman commented on Jun 21, 2016

    @julielerman

    @ajcvickers when Attaching a graph (no previously tracked entities) and child does NOT have it's key value filled, it becomes Added. When there is a a value in key, it becomes Unchanged. I did not expect this. Is Attach now reading key values to make state decisions? Did I miss that explanation somewhere?

    edit: yeah okay I see that re-reading the original post in this thread....

  16. sjb-sjb commented on Aug 13, 2016

    @sjb-sjb

    It's great to follow this discussion, especially given how long these challenges have been kicking around.

    I believe the TrackGraph pattern described by @julielerman may be superceded by the IsKeySet approach, i.e. simply use store-generated keys and then do one of the following: either
    (a) Attach copies of the entities that already exist in the store ("b" in @aflx's example) with their primary keys set, and then Add the (root of the) new entities; or
    (b) Refer to existing entities by putting their store-generated keys in the new entities, and then Add the (root of the) new entities.

    @julielerman 's comment of June 21, and the description of Attach in @rowanmiller 's original posting, seem to say that in case (a) you could use Attach instead of Add for the new entities. The new entities' store-generated keys will not have been set and therefore the Attach will actually set the state to Added. In other words you can just construct the complete graph, including store-generated Id's in the case where the entity is a copy of an object already in the data store, and just Attach the whole thing. Or you can refer to the existing objects by Id instead of by reference, in which case you can either Add or Attach the graph.

    Have I gotten that right? It would be great to have an update to @julielerman 's April MSDN article that takes into account the June discussion above.

  17. sjb-sjb commented on Aug 15, 2016

    @sjb-sjb

    Cool, thanks!

    Sent from my iPhone

    On Aug 13, 2016, at 2:07 AM, Erik Ejlskov Jensen [email protected] wrote:

    @sjb-sjb did you see this https://msdn.microsoft.com/magazine/mt767693 ?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub, or mute the thread.

  18. modified the milestones: , 1.0.0 on Oct 15, 2022
  19. removed their assignment
    on Sep 1, 2024
  20. added theissue type on Jun 15, 2025
  21. mwpowellhtx commented on Dec 12, 2025

    @mwpowellhtx

    We have the TrackGraph API for exactly this purpose.

    Not sure the veracity of this claim; as it seems children are prematurely being attached prior to receiving a node callback opportuinity. At which point we would calculate state and so forth, and decide the best course of action, followed sometimes by save changes, at which point those naughty zero identifiers would be triggered to temporarily value generate themselves. This: not happening, in our scenarios...

    I am using 8 (8.0.7) and this STILL seems like a perennial penultimate issue, again. Tracking from a nominally disconnected root instance, and children are STILL being prematurely attach.

    Because it is gumming up the works, not helping, but rather, proving to be more of a hindrance (read: liability) than a benefit (read: asset), for an arbitrarily n-level disconnected graph scenario. We will not even broach navigation, which are all nominally configured forward only parent-child; no children have navigation to parent, to keep it simple.

    Much of the examples are overly simplified, usually with a save changes invoked AFTER tracking graph, which I can tell you for even a minimally complex domain tree/graph, we generally want to calculate state then save changes immediately. That's assuming children have not been prematurely attached to the context.

    In our scenarios, we are likely to receive numerous such transient entities from upstream API, and some generated from local application gestures and what not. All disconnected, should be graph tracked in order to properly reconcile with the database, perform appropriate upserts, deletions, etc.

    What is the guidance and/or solution on this aspect? Do we need to negotiate the navigation ourselves for a given node, entry, or what not, as received during the course of graph tracking? It seems perhaps "yes", but the commentary around these nuances seems few if far between.

  22. roji commented on Dec 12, 2025

    @roji
    Member

    @mwpowellhtx let's keep that in conversation in #37339 which you opened for this topic. This here is an issue from 2016.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions