I am trying to edit the contents of a pivot table in EntityFramework CodeFirst.

I am using .NET Framework 4.6.1 with EntityFramework 6.1.3.

I have my models setup like this:

```
public class Post
{
    /// <summary>
    /// The post's id in the database
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// The the categories the post belongs to
    /// </summary>
    [InverseProperty("Posts")]
    public virtual ICollection<Category> Categories { get; set; }

    /// <summary>
    /// The title of the post
    /// </summary>
    [Required]
    public string Title { get; set; }

    /// <summary>
    /// The content of the post
    /// </summary>
    [Required]
    public string Content { get; set; }

    /// <summary>
    /// The moment the post was made
    /// </summary>
    public DateTime? TimeStamp { get; set; }
}

public class Category
{
    /// <summary>
    /// The id of the category in the database
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// The posts that belong to this category
    /// </summary>
    [InverseProperty("Categories")]
    public virtual ICollection<Post> Posts { get; set; }

    /// <summary>
    /// The name of the category
    /// </summary>
    [Required]
    public string Name { get; set; }
}

```

As you can see a `Post` can belong to many `Category`'s and a `Category` can have many `Post`'s

My problem occurs when I try to update a post and change it's `Category`'s.

Controller:

```
[HttpPut]
[ResponseType(typeof(void))]
public IHttpActionResult PutPost(int id, Post post)
{
    if (id != post.Id)
    {
        return BadRequest();
    }

    var entry = db.Entry(post);
    entry.State = EntityState.Modified;

    // Created at must not be updated.
    entry.Property(x => x.TimeStamp).IsModified = false;

    // Also attatch categories
    foreach (var category in post.Categories) // For the example, I assume all user input is correct.
    {
        db.Categories.Attatch(category); // This is not working
    }

    try
    {
        db.SaveChanges();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!PostExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return StatusCode(HttpStatusCode.NoContent);
}

```

**The problem:**

Everything works fine: I can update the `Title` and `Content` of a `Post` no problem. But the `Post.Categories` is not updated in the database. 

I have seen people updating many-to-many relationships by first getting the entity from the database and using `Include(x => x.Relation)` and then editing the everything inside that object. However, that requires loading a bulk of data from the database which is negated directly after. That seems bad practice to me.

**The question:**
How do I properly update a many-to-many relationship in EntityFramework, without loading unnecessary data from the database?