title: Updating a many-to-many relationship
body: <p>I've asked the question a few different times in a few different ways and I haven't yet gotten any responses.  I'm trying again because I feel like my solution is too convoluted and I must be missing something simpler to do.</p>
  
  <p>Using EF 4.1, POCO, DbContext API, AutoMapper, and Razor in an MVC 3 application.</p>
  
  <p>I have a many-to-many relationship between two of my entities:  Proposals and CategoryTags.  I can successfully map (Automapper) a Proposal to my ProposalViewModel including the collection of CategoryTags.</p>
  
  <p>In my View, I use javascript to allow the user to add, update, and remove tags by dynamically creating  elements, each one that stores the ID of the chosen tag.  </p>
  
  <p>I can successfully post my ViewModel back to my controller with it's CategoryTags collection populated (although only with the ID property for each CategoryTag).</p>
  
  <p><strong>When that ViewModel is posted back to my controller, I don't know how to get those tags from the ViewModel and add them to my Model in such a way that db.SaveChanges() updates the database properly.</strong></p>
  
  <p>The <em>only</em> way I've had any success is to disconnect the CategoryTags collection in mapping (by namig them differently), iterate through each tag and manually look it up in my context and then call the .add() method.  This is sloppy for a number of reasons which leads me to believe I'm doing it wrong.</p>
  
  <p>Can anyone offer any direction at all?</p>
  
  <p>UPDATE:</p>
  
  <p>For anyone who is interested, my functional code:</p>
  
  <pre><code>            Dim p As New Proposal
              Dim tempTag As CategoryTag
              p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
  
              db.Proposals.Attach(p)
              db.Entry(p).Collection("CategoryTags").Load()
  
              For Each ct In pvm.Tags
                  tempTag = db.CategoryTags.Find(ct.Id)
  
                  If tempTag Is Nothing Then
                      Continue For
                  End If
  
                  If ct.Tag = "removeMe" Then
                      p.CategoryTags.Remove(tempTag)
                      Continue For
                  End If
  
                  p.CategoryTags.Add(tempTag)
              Next
  
  
              db.Entry(p).State = EntityState.Modified
              db.SaveChanges()
              Return RedirectToAction("Index")
  </code></pre>