title: ASP.NET Core MVC Edit CheckBoxList values in Database
body: <p>I'm having trouble understanding how to update the CheckBoxList values to the CustomerDevice table in my Database on the [HttpPost] Edit Action Method CustomerDeviceController.</p>
  
  <p>My Index Action Method for the CustomerDeviceController displays a list of Customers from my Customers table. I have an ActionLink labeled "Edit" that passes the CustId value to the CustomerDeviceController [HttpGet] Edit(int? id) Action Method which then displays all selected DevId values assigned to the CustId to the CheckBoxList, this part works fine.</p>
  
  <p>When I try to update the CheckBoxList values now I get the following error message below. I was told that I would need to loop through and delete the DevId values before I could update them. This is the part I'm having trouble understanding.</p>
  
  <p><strong>Error Message when updating CheckBoxList</strong></p>
  
  <p>An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code</p>
  
  <p>Additional information: The instance of entity type 'CustomerDevice' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.</p>
  
  <p><strong>Models</strong></p>
  
  <pre><code>    public class CheckBoxListItem
  {
      public int ID { get; set; }
      public string Display { get; set; }
      public bool IsChecked { get; set; }
  }
  
      public class Customer
  {
      public int CustId { get; set; }
      public string CustDisplayName { get; set; }
      ...
  }
  
      public class Device
  {
      public int DevId { get; set; }
      public string DevType { get; set; }
  }
  
      public class CustomerDevice
  {
      public int CustId { get; set; }
      public int DevId { get; set; }
  
      public Customer Customer { get; set; }
      public Device Device { get; set; }
  }
  </code></pre>
  
  <p><strong>ViewModels</strong></p>
  
  <pre><code>    public class CustomerDeviceFormViewModel
  {
      public int CustId { get; set; }
      public string CustDisplayName { get; set; }
      public List&lt;CheckBoxListItem&gt; Devices { get; set; }
  }
  </code></pre>
  
  <p><strong>CustomerDeviceController</strong></p>
  
  <pre><code>public ActionResult Create(int? id)
      {
          if (id == null)
          {
              return NotFound();
          }
  
          var customervm = new CustomerDeviceFormViewModel();
          {
              Customer customer = db.Customers.SingleOrDefault(c =&gt; c.CustId == id);
  
              if (customer == null)
              {
                  return NotFound();
              }
  
              customervm.CustId = customer.CustId;
              customervm.CustDisplayName = customer.CustDisplayName;
  
              // Retrieves list of Devices for CheckBoxList
              var deviceList = db.Devices.ToList();
              var checkBoxListItems = new List&lt;CheckBoxListItem&gt;();
              foreach (var device in deviceList)
              {
                  checkBoxListItems.Add(new CheckBoxListItem()
                  {
                      ID = device.DevId,
                      Display = device.DevType,
                      IsChecked = false //On the create view, no devices are selected by default
                  });
              }
  
              customervm.Devices = checkBoxListItems;
              return View(customervm);
          }
      }
  
  
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Create(CustomerDeviceFormViewModel vm)
      {
          if (ModelState.IsValid)
          {
              foreach (var deviceId in vm.Devices.Where(x =&gt; x.IsChecked).Select(x =&gt; x.ID))
              {
                  var customerDevices = new CustomerDevice
                  {
                      CustId = vm.CustId,
                      DevId = deviceId
                  };
  
                  db.CustomerDevices.Add(customerDevices);
              }
  
              db.SaveChanges();
              return RedirectToAction("Index");
          }
  
          return View(vm);
      }
  
  
      public ActionResult Edit(int? id)
      {
          Customer customer = db.Customers.SingleOrDefault(c =&gt; c.CustId == id);
          if (customer == null)
          {
              return NotFound();
          }
          // Get all devices
          var deviceList = db.Devices.ToList();
          // Get the selected device ID's for the customer
          IEnumerable&lt;int&gt; selectedDevices = db.CustomerDevices
              .Where(x =&gt; x.CustId == id).Select(x =&gt; x.DevId);
          // Build view model
          var model = new CustomerDeviceFormViewModel()
          {
              CustId = customer.CustId,
              CustDisplayName = customer.CustDisplayName,
              Devices = deviceList.Select(x =&gt; new CheckBoxListItem()
              {
                  ID = x.DevId,
                  Display = x.DevType,
                  IsChecked = selectedDevices.Contains(x.DevId)
              }).ToList()
          };
          return View(model);
      }
  
  
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Edit(CustomerDeviceFormViewModel vmEdit)
      {
          if (ModelState.IsValid)
          {
              Customer customer = db.Customers
                         .Include(c =&gt; c.CustomerDevices)
                         .SingleOrDefault(c =&gt; c.CustId == vmEdit.CustId);
  
              if (customer == null)
              {
                  return NotFound();
              }
  
              IEnumerable&lt;int&gt; selectedDevices = vmEdit.Devices.Where(x =&gt; x.IsChecked).Select(x =&gt; x.ID);
  
              // Remove all selected devices for this customer
              foreach (int removeId in selectedDevices)
              {
                  customer.CustomerDevices.Clear();
              }
  
  
              // Add the new selected devices
              foreach (int deviceId in selectedDevices)
              {
                  CustomerDevice customerDevice = new CustomerDevice
                  {
                      CustId = customer.CustId,
                      DevId = deviceId
                  };
                  customer.CustomerDevices.Add(customerDevice);        
              }
  
              // Update the customer
              db.Customers.Update(customer); //or just db.Update(customer); same thing
              //                               // Save and redirect
              db.SaveChanges();
              return RedirectToAction("Index");
          }
  
          return View(vmEdit);
      }
  </code></pre>
  
  <p><strong>Edit View</strong></p>
  
  <pre><code>    &lt;div class="form-group"&gt;
      Please select the Devices to assign to &lt;b&gt;@Html.DisplayFor(c =&gt; c.CustDisplayName)&lt;/b&gt;
  &lt;/div&gt;
  
  &lt;div class="form-group"&gt;
      @Html.EditorFor(x =&gt; x.Devices)
  &lt;/div&gt;
  
  @Html.HiddenFor(c =&gt; c.CustId)
  
  &lt;div class="form-group"&gt;
      &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>Shared/EditorTemplates/CheckBoxListItem.chtml</strong></p>
  
  <pre><code>&lt;div class="checkbox"&gt;
  &lt;label&gt;
      @Html.HiddenFor(x =&gt; x.ID)
      @Html.CheckBoxFor(x =&gt; x.IsChecked)
      @Html.LabelFor(x =&gt; x.IsChecked, Model.Display)
  &lt;/label&gt;
  &lt;br /&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>WebFormContext</strong></p>
  
  <pre><code>public class WebFormContext : DbContext
  {
      public WebFormContext(DbContextOptions&lt;WebFormContext&gt; options)
          : base(options)
      { }
  
      public DbSet&lt;Customer&gt; Customers { get; set; }
      public DbSet&lt;State&gt; States { get; set; }
      public DbSet&lt;Device&gt; Devices { get; set; }
      public DbSet&lt;CustomerDevice&gt; CustomerDevices { get; set; }
  
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
          modelBuilder.Entity&lt;Customer&gt;()
              .HasKey(c =&gt; c.CustId);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustDisplayName)
              .HasColumnType("varchar(100)")
              .HasMaxLength(100)
              .IsRequired();
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustFirstName)
              .HasColumnType("varchar(50)")
              .HasMaxLength(50);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustLastName)
              .HasColumnType("varchar(50)")
              .HasMaxLength(50);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustCompanyName)
              .HasColumnType("varchar(50)")
              .HasMaxLength(50);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustAddress)
              .HasColumnType("varchar(100)")
              .HasMaxLength(100)
              .IsRequired();
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustPhoneNumber)
              .HasColumnType("varchar(12)")
              .HasMaxLength(12);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustMobileNumber)
              .HasColumnType("varchar(12)")
              .HasMaxLength(12);
  
          modelBuilder.Entity&lt;Customer&gt;()
              .Property(c =&gt; c.CustEmailAddress)
              .HasColumnType("varchar(320)")
              .HasMaxLength(320);
  
          modelBuilder.Entity&lt;Device&gt;()
              .HasKey(d =&gt; d.DevId);
  
          modelBuilder.Entity&lt;Device&gt;()
              .Property(d =&gt; d.DevType)
              .HasColumnType("varchar(50)")
              .HasMaxLength(50)
              .IsRequired();
  
          modelBuilder.Entity&lt;CustomerDevice&gt;()
              .HasKey(cd =&gt; new { cd.CustId, cd.DevId });
      }
  }
  </code></pre>