title: How do I ModelBind a many-to-many relationship with MVC 3 and Entity Framework Code First?
body: <p>I'm coming across the same problem in my MVC 3 applications. I've got a view to create an new product and that product can be assigned to one or more categories. Here are my EF Code First Model Classes:</p>
  
  <pre><code>public class Product 
  {
      public int ProductID { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;Category&gt; Categories { get; set; }
  }
  
  public class Category 
  {
      public int CategoryID { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;Product&gt; Products { get; set; }
  }
  </code></pre>
  
  <p>So, I create a view model for the create product view and include the product and a list of the categories:</p>
  
  <pre><code>public class ProductEditViewModel
  {
      public Product Product { get; set; }
      public List&lt;SelectListItem&gt; CategorySelections { get; set; }
  
      public ProductEditViewModel(Product product, List&lt;Category&gt; categories)
      {
          this.Product = product;
          CategorySelections = categories.Select(c =&gt; new SelectListItem()
          {
              Text = c.Name,
              Value = c.CategoryID.ToString(),
              Selected = (product != null ? product.Categories.Contains(c) : false)
          }).ToList();
      }
  }
  </code></pre>
  
  <p>So, I render a view with an input for the name and a list of checkboxes for each category (named "Product.Categories"). When my form gets posted back I want to save the product with its associated categories (or if the ModelState is invalid, to redisplay the view with the category selections the user made intact).</p>
  
  <pre><code>[HttpPost]
  public ActionResult Create(Product product)
  {
      if (ModelState.IsValid)
      {
          db.Products.Add(product);
          db.SaveChanges();
          return RedirectToAction("Index");
      }
  
      return View(new ProductEditViewModel(product, db.Categories.ToList()));
  }
  </code></pre>
  
  <p>When i do that and select one or more categories, the ModelState is invalid and it returns the Edit view with the following validation error:</p>
  
  <blockquote>
    <p>The value '25,2' is invalid. // 25 and 2 being the CategoryIDs</p>
  </blockquote>
  
  <p>It makes sense to me that it can't bind 25 and 2 into actual category objects, but is there a standard way to use a custom ModelBinder that would allow me to translate IDs into Categories and attach them to the context?</p>