entity-framework-core

EF Core : add object to set with existing child objects causes duplicate key exceptions


I have these models:

public class A
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public B Child { get; set; }
}

public class B
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

I am deserialzing a JSON object in this format:

{
    name: "Test",
    child: {
        id: "1231313131"
    }
}

The object is a new record to be inserted but the child object already exists and I have it's ID.

I am then doing

DbContext.Set.Add(deserializedObject)

However EF Core is trying to insert my child object again into the database.

How can I stop this behaviour without fetching the existing child object from the database first? We have several instances of this and would like to fix it in a generic way please


Solution

  • If the entities have generated keys, use Update or Attach instead of Add. Add attaches all accessible objects in the Added state.

    If you don't want to persist the child object, what you probably need is :

    myContext.Attach(orderWithProduct);
    

    Attach and Update on the other hand check the primary key values to determine if an object is new or existing.

    As the docs explain, for Attach :

    For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state.

    And for Update:

    For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state.