'How can I update an instance that has a many-to-many relationship, using Blazer.Server with .net6?

I have a Blazor.Server app with crud operations. I keep getting an error when I try to update an instance that has relationship with another entity.

Error: System.ApplicationException: The instance of entity type 'Person' cannot be tracked because another instance with the key value '{Id: 3}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

public class PersonDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Person_PracticeAreaDTO> Person_PracticeAreas { get; set; } = new List<Person_PracticeAreaDTO>();
}

public class PracticeAreaDTO
{
    public int Id { get; set; }
    public string? Title { get; set; }
    public virtual List<Person_PracticeAreaDTO> Person_PracticeAreas { get; set; } = new List<Person_PracticeAreaDTO>();
}

public class Person_PracticeAreaDTO
{
    public int Id { get; set; }
    public int PersonId { get; set; }
    public PersonDTO Person { get; set; }

    public int PracticeAreaId { get; set; }
    public PracticeAreaDTO PracticeArea { get; set; }
}


public MappingProfile()
{
   CreateMap<PracticeAreaDTO, PracticeArea>().ReverseMap();
   CreateMap<PersonDTO, Person>().ReverseMap();
   CreateMap<PostDTO, Post>().ReverseMap();
   CreateMap<Person_PracticeArea, Person_PracticeAreaDTO>().ReverseMap();
}

public async Task<PracticeAreaDTO?> UpdatePracticeArea(PracticeAreaDTO practiceAreaDTO)
{
    try
    {
        PracticeArea practiceAreaDb = await applicationDbContext.PracticeAreas.FindAsync(practiceAreaDTO.Id);
        PracticeArea practiceArea = mapper.Map<PracticeAreaDTO, PracticeArea>(practiceAreaDTO, practiceAreaDb);

        // Add more details
        applicationDbContext.PracticeAreas.Update(practiceArea);
        await applicationDbContext.SaveChangesAsync();
        return mapper.Map<PracticeArea, PracticeAreaDTO>(updatedPracticeArea.Entity);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

In PracticeAreaUpsert.razor:

await PracticeAreaRepository.UpdatePracticeArea(PracticeAreaModel);

I get the error only when I try to edit the PracticeArea instance that has a relationship with a Person instance. How can I edit the instance and propagate it to its relationships?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source