'EF Core Tracking Error while adding a record into database

I have the following classes and methods to add an appointment:

public async Task<bool> UpdatePatientAppointmentAsync(AppointmentData appointment)
{
    int res = 0;

    using (var scope = _scopeFactory.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

        // appointment.AppointmentId = 0;
        try
        {
            context.Appointments.Add(appointment);

            res = await context.SaveChangesAsync();

            if (res > 0)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

public async Task<List<AppointmentData>> GetPatientAppointmentsAsync(Patient patient)
{
    using (var scope = _scopeFactory.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        var appts = await context.Appointments
                                 .Include(d => d.Doctor)
                                 .Include(d => d.Patient)
                                 .AsNoTracking()
                                 .Where(p => p.PatientId == patient.PatientId)
                                 .ToListAsync();

        DisplayStates(context.ChangeTracker.Entries());

        return appts;
    }
}

public class Doctor
{
    [Key]
    public int DoctorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Specialization { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Designation { get; set; }
    public bool IsDeleted { get; set; }
}

public class AppointmentData
{
    [Key]
    public int AppointmentId { get; set; }
    public string Subject { get; set; }
    public string Location { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string Description { get; set; }
    public string EventType { get; set; }
    public bool IsAllDay { get; set; }
    public string RecurrenceRule { get; set; }
    public string RecurrenceException { get; set; }
    public Nullable<int> RecurrenceID { get; set; }
    public int PatientId { get; set; }
    public Patient Patient { get; set; }
    public int DoctorId { get; set; }
    public Doctor Doctor { get; set; }  
}

I load appointments and doctors as follows:

protected override async Task OnInitializedAsync()
{
    appointments = await DataService.GetPatientAppointmentsAsync(AppState.SelectedPatient);
    doctors = await DataService.GetAllDoctorsAsync();
}

and then save an appointment like this:

appt.Patient = AppState.SelectedPatient;
appt.PatientId = AppState.SelectedPatient.PatientId;
appt.Doctor = doctors.First(d => d.DoctorId == Int32.Parse(fn));
appt.DoctorId = Int32.Parse(fn);

var res1 = await DataService.UpdatePatientAppointmentAsync(appt);

DataService is registered as follows:

builder.Services.AddScoped<DataService>();

When UpdatePatientAppointmentAsync is called, I get the following EF Core error:

The instance of entity type 'Doctor' cannot be tracked because another instance with the same key value for {'DoctorId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

I don't want to update or track the Doctor entity and I don't understand why it's being tracked. When loading all data, I am using .AsNoTracking(). Is it possible to turn off tracking for Doctor entity? Or any other pointers as how to resolve this error?



Sources

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

Source: Stack Overflow

Solution Source