title: Many-to-Many insert logic
body: <p>With Entity Framework I'm trying to set up a many to many relationship in a simple blog asp.net mvc 4 app. My models are as follows:</p>
  
  <pre><code>public class BlogPost
      {
          [Key]
          public string Id { get; set; }
          public DateTime DateCreated { get; set; }
  
          [Required]
          public string Title { get; set; }
          public string Image { get; set; }
          public string ThumbImage { get; set; } 
          public ICollection&lt;BlogCategory&gt; Categories { get; set; }
  
          [AllowHtml]
          public string Content { get; set; }        
      }
  
      public class BlogCategory
      {
          [Key]
          public string Name { get; set; }
  
          public virtual ICollection&lt;BlogPost&gt; Posts { get; set; }
      }
  </code></pre>
  
  <p>The blog categories cannot be an enum as new ones may want to be added, so a collection is needed. The Category is simple, just the name, and a way to navigate to all posts with the given category. The problem is when creating a new BlogPost. In an ideal world the following would happen.</p>
  
  <pre><code>private BlogPost post = new BlogPost
      {
          Title = "Blog Entry One",
          Categories = new List&lt;BlogCategory&gt;()
              {
                  new BlogCategory {Name = "Web"},
                  new BlogCategory() {Name = "C#"}
              },
          Content =
              "Aliquam sem quam, posuere eget tellus in, porta semper dolor. Morbi aliquam placerat urna ut."
      };
  </code></pre>
  
  <p>When the context is saved if a BlogCategory with the name "Web" is already in the database then reference to it. If not create the new entry.</p>
  
  <p>At the moment EF throws an error that the key is already in use. Hope someone can help!</p>