title: ASP.NET Core - The instance of entity type cannot be tracked
body: <p>I've encountered an issue when trying to update my context in my Edit action:</p>
  
  <pre><code>[HttpPost]
  public IActionResult Edit(Model.LeaveApplication leaveApplication) {
  
  ViewBag.Title = "Edit Leave Application";
  ViewBag.leavePeriodList = context.LeavePeriod.ToList();
  ViewBag.LeaveTypeList = context.LeaveType.ToList();
  
  try {    
      if (ModelState.IsValid) {    
          if (!validateDateRanges(leaveApplication, "edit")) {    
              return View(leaveApplication);
          }
  
          leaveApplication.NumDays = (float)CalculateNoOfDays(leaveApplication);
          context.LeaveApplication.Update(leaveApplication);
          context.SaveChanges();
  
          return RedirectToAction("Index");
      }    
  }
  catch (DbUpdateException) {    
      ModelState.AddModelError("", "Unable to edit leave application. " +
      "Please try again, and if the problem persists, " +
      "please see your system administrator.");
  }              
      return View(leaveApplication);
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/ZSwYZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZSwYZ.png" alt="enter image description here"></a></p>
  
  <p>What I am trying to do is to check if there is more than 1 records in order to validate date ranges. If there is only 1 record, I will then skip the validation and proceed to update the context. However, I get an error saying: </p>
  
  <blockquote>
    <p>The instance of entity type 'LeaveApplication' cannot be tracked because another instance of this type with the same key is already being tracked.</p>
  </blockquote>
  
  <p>What is causing this problem?</p>
  
  <p>Here is my constructor code:</p>
  
  <pre><code>public class LeaveApplicationController : Controller {
  
      LeaveDBContext context;
      private readonly UserManager&lt;ApplicationUser&gt; userManager;
      private readonly SignInManager&lt;ApplicationUser&gt; signInManager;
  
      public LeaveApplicationController(LeaveDBContext context, UserManager&lt;ApplicationUser&gt; userManager, SignInManager&lt;ApplicationUser&gt; signInManager) {
  
          this.context = context;
          this.userManager = userManager;
          this.signInManager = signInManager;
      }
  }
  </code></pre>