title: Instance cannot be tracked because another instance with the same key is already tracked
body: <p>I just started with asp.net core MVC by developing a <strong>Car Rental</strong> application and I'm using EF Core for working with the database. The problems comes when I'm trying to update a record from database.
  It gives me the folloing exception:</p>
  <p><strong>InvalidOperationException</strong>: The instance of entity type 'Car' cannot be tracked because another instance with the same key value for {'CarID'} 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.</p>
  <p>Here's my code for updating a car:</p>
  <p>Repository:</p>
  <pre><code>public Car GetCarByID(int carId)
  {
      return _context.Cars.Where(c=&gt; c.CarID == carId).Include(c=&gt;c.Category)
                                                      .Include(c=&gt;c.Type)
                                                     .Include(c=&gt;c.CarLocations).ThenInclude(c=&gt;c.Location)
                                                     .FirstOrDefault();
  }
  </code></pre>
  <pre><code> public void UpdateCar(Car car)
   {
       _context.Update(car);
   }
  </code></pre>
  <p>Controller car update code:</p>
  <pre><code> [HttpGet]
          public async Task&lt;IActionResult&gt; Edit(int id)
          {
              await SeedCarView();
  
              var carToEdit = _carsRepo.GetCarByID(id);
  
              if (carToEdit == null)
              {
                  return NotFound();
              }
  
              return View(carToEdit);
          }
  </code></pre>
  <pre><code>[HttpPost]
          public async Task&lt;IActionResult&gt; Edit(Car car)
          {
              await SeedCarView();
  
              if (ModelState.IsValid)
              {
                  /*get selections from dropdown form*/
                  string categSelection = Request.Form[&quot;Category_Name&quot;].ToString();
                  string bodySelection = Request.Form[&quot;TypeName&quot;].ToString();
                  var selectedLocations = Request.Form[&quot;AreChecked&quot;].ToList();
  
                  var selectedCategory = await _categoriesRepo.GetCategoryByIDAsync(categSelection);
                  var selectedBodyType = await _typesRepo.GetBodyTypeByNameAsync(bodySelection);
  
                  car.Category = selectedCategory;
                  /*Increment the number of cars in this category*/
                  car.Category.NumberOfCars = car.Category.Cars.Count + 1;
                  car.Type = selectedBodyType;
  
                  foreach (var sel in selectedLocations)
                  {
                      CarLocation carLocation = new CarLocation
                      {
                          Car = car
                      };
  
                      var location = _locationsRepo.GetLocationByID(Int32.Parse(sel));
                      carLocation.Location = location;
  
                      car.CarLocations.Add(carLocation);
                  }
  
                  _carsRepo.UpdateCar(car);
                  await _carsRepo.SaveAsync();
  
                  return RedirectToAction(&quot;Listing&quot;);
              }
  
              return View(car);
          }
  </code></pre>
  <pre><code>
  private async Task SeedCarView()
          {
              var categories = await _categoriesRepo.GetCategoriesAsync();
              var bodyTypes = await _typesRepo.GetBodyTypesAsync();
              var locations = await _locationsRepo.GetLocationsAsync();
  
              List&lt;string&gt; categorieNames = new List&lt;string&gt;();
              List&lt;string&gt; typeNames = new List&lt;string&gt;();
  
              /*get the existing categories name and body types name*/
              foreach (var item in categories)
                  categorieNames.Add(item.Category_Name);
              foreach (var item in bodyTypes)
                  typeNames.Add(item.Name);
  
              ViewBag.Category_Names = categorieNames;
              ViewBag.TypeNames = typeNames;
              ViewBag.LocationNames = locations;
          }
  </code></pre>
  <p>Here's the Service Configuration methode:</p>
  <pre><code>public void ConfigureServices(IServiceCollection services)
          {
              services.AddControllersWithViews();
              services.AddDbContext&lt;CarRentalContext&gt;(item =&gt; item.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
              services.AddScoped&lt;ICarsRepository, CarsRepository&gt;();
              services.AddScoped&lt;ICarCategoryRepository, CarCategoryRepository&gt;();
              services.AddScoped&lt;ICarTypeRepository, CarTypeRepository&gt;();
              services.AddScoped&lt;ILocationsRepository, LocationsRepository&gt;();
          }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/zXcLd.png" rel="nofollow noreferrer">Exception at Update methode</a></p>
  <p>Please help me to fix this issue. I'm stuck at this for more than 2 days and I don't understand where's the problem.</p>
  <p><strong>Update</strong>:</p>
  <p>I've changed my Update methode in Repository with the following code:</p>
  <pre><code> public void UpdateCar(Car car)
          {
              var existingCar = GetCarByID(car.CarID);
              _context.Entry(existingCar).CurrentValues.SetValues(car);
  
              //_context.Update(car);
          }
  </code></pre>
  <p>and the code in the POST action:</p>
  <pre><code>    foreach (var sel in selectedLocations)
                  {
                      var location = _locationsRepo.GetLocationByID(Int32.Parse(sel));
  
                      CarLocation carLocation = new CarLocation
                      {
                          CarID = car.CarID,
                          LocationID = location.Location_ID,
                          Car = car,
                          Location = location
                      };
  
                      car.CarLocations.Add(carLocation);
                  }
  </code></pre>
  <p>but now only the car instance is updated, without childs like CarCategory, Locations and CarType.</p>