The instance of entity type 'User' cannot be tracked because another instance with the same key value for is already being tracked. Not structural

44 views Asked by At

For a project I'm trying to make a certain User a Trainer of a given Club. For this, I created an entity, Trainer which has a one to one with User. The club then has Collections of Users and Trainers.

It all goes fine when adding trainers to the club, and they are added correctly to the database. But once I also add a certain role to the user, it gives me a System.InvalidOperationException: The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked error.

The weird thing, is that the first time, I send the request, it works, the second time it gives this error. When i restart the debug, and execute the endpoint again, it does work, but then when I upgrade another user, it again gives this error.

Club navigation props

public IReadOnlyCollection<Trainer> Trainers => _trainers;
public IReadOnlyCollection<User> Members => _members;

User navigation props

public IReadOnlyCollection<Trainer> Trainers => _trainers;

Trainer navigation props

public UserId UserId { get; private set; }
public User? User { get; private set; } 
public ICollection<Club> Clubs => _clubs;

Handler to create trainer and add user role

    public async Task<Result> Handle(AddTrainerToClubCommand command,
        CancellationToken cancellationToken)
    {
        var club = await _clubRepository.FindByIdAsync(command.ClubId, 
            x => x.Include(club => club.Trainers).ThenInclude(t => t.User), cancellationToken: cancellationToken);
        
        if (club is null)
        {
            return Result.NotFound(typeof(Club));
        }
        
        // check if trainer is already trainer in club
        if (club.Trainers.Any(trainer => trainer.UserId.Equals(UserId.Create(command.AddTrainerToClubRequest.UserId))))
        {
            return Result.Failure(ClubErrors.TrainerAlreadyInClub);
        }
        
        var user = await _userRepository.FindByIdAsync(UserId.Create(command.AddTrainerToClubRequest.UserId), cancellationToken: cancellationToken);
        
        if (user is null)
        {
            return Result.NotFound(typeof(User));
        }
        
        var trainer = new Trainer(TrainerId.Create(Guid.NewGuid()), user);
        club.AddTrainer(trainer);
        
        await _trainerRepository.AddAsync(trainer, cancellationToken);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Result.Success();
    }
}

inside of the Trainer constructor

    public Trainer(TrainerId id,
        User user)
        : base(id)
    {
        UserId = user.Id;
        User = user;
        User.AddRole(Role.ClubTrainer); <-- once I add this line of code, it gives the error
    }

EDIT: I’m using ef-core 8.0.0.

The roles is an custom entity

public class Role : Enumeration<Role>
{
    public static readonly Role RegisteredUser = new Role(1, "RegisteredUser");
    public static readonly Role DummyRole = new Role(2, "DummyRole");
    public static readonly Role ClubAdmin = new Role(3, "ClubAdmin");
    public static readonly Role ClubOwner = new Role(4, "ClubOwner");
    public static readonly Role ClubTrainer = new Role(5, "ClubTrainer");
    
    public Role(
        int id,
        string name)
        : base(id, name)
    {
    }

    public ICollection<Permission> Permissions { get; set; } = new List<Permission>();
    public ICollection<User> Users { get; set; } = new List<User>();
}

the AddRole is nothing more then a Roles.add(role) in the collection of roles in the user entity

0

There are 0 answers