Skip to content

Exception replacing multi-level relationship in EF7 #30135

@iheb719

Description

@iheb719

Ask a question

I have the following model

public partial class Parent
{
    public int IdParent { get; set; }

    public virtual ICollection<FirstChild> FirstChild{ get; set; } = new List<FirstChild>();
}

public partial class FirstChild
{
    public int IdFirstChild { get; set; }

    public virtual ICollection<SecondChild> SecondChild { get; set; } = new List<SecondChild>();
}

public partial class SecondChild 
{
    public int IdSecondChild  { get; set; }

    public virtual ICollection<ThirdChild> ThirdChild{ get; set; } = new List<ThirdChild>();
}

public partial class ThirdChild
{
    public int IdThirdChild { get; set; }

    public String SomeProperty{ get; set; }
}

I update Parent with all it's relationships it this way :

var parentDB = _context.Parent.Single(x => x.IdParent == {id})
.Include(x => x.FirstChild)
.ThenInclude(x => x.SecondChild)
.ThenInclude(x => x.ThirdChild);

parentDb.FirstChild = {newCollectionValuesList}

_context.SaveChanges();

This works with EF Core 6 :

  • If in {newCollectionValuesList}, there is an element that already exists in parentDb.FirstChild (same ID), it get updated (with all its hierarchy)
  • If if does not exists, it will be added
  • If it exists but was not specified in {newCollectionValuesList}, it get deleted

When I upgraded to EF Core 7, I started to have this error :

The instance of entity type 'SecondChild' cannot be tracked because another instance with the key value '{IdSecondChild: XXXX}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached

I tried to add .AsNoTracking() in the query to resolve this, but my entities won't be updated

I don't want to loop manually through all the relationship and manually add the conditions to update the child elements

I didn't find anything related to that in What's new in EF7 nor in Breaking changes in EF7

This is a sample project with integration tests to reproduce the problem

Is this a bug ? because it works in EF6
Same result using dotnet6 and dotnet7

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions