I had this create method:
[HttpPost]
[Route("")]
/// <summary>
/// Create a team
/// </summary>
/// <param name="model">The team model</param>
/// <returns>The modified team model</returns>
public async Task<IHttpActionResult> Create(TeamBindingViewModel model)
{
    // If our model is invalid, return the errors
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    // Get all our colours
    var colours = await this.colourService.GetAllAsync();
    // Create our new model
    var team = new Team()
    {
        Name = model.Name,
        Sport = model.Sport
    };
    // For each colour, Add to our team
    team.Colours = colours.Where(m => model.Colours.Any(c => c.Id == m.Id)).ToList();
    // Create our team
    this.service.Create(team);
    // Save our changes
    await this.unitOfWork.SaveChangesAsync();
    // Assign our Id to our model
    model.Id = team.Id;
    // Return Ok
    return Ok(model);
}
As you can see, when a Team is created, I need to add the Colours to the lookup table. To do this, I get the Colours from the database and then filter them by the colours that were passed as part of the model.
That tells Entity Framework that these Colours are not new entities, so it just creates a reference in the lookup table rather than creating new Colours.
Now I want to do the same for the update method.
I tried this:
[HttpPut]
[Route("")]
/// <summary>
/// Update a team
/// </summary>
/// <param name="model">The team model</param>
/// <returns>The modified team model</returns>
public async Task<IHttpActionResult> Update(TeamBindingViewModel model)
{
    // If our model is invalid, return the errors
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    // Get our current team
    var team = await this.service.GetAsync(model.Id, "Colours");
    // Get all our colours
    var colours = await this.colourService.GetAllAsync();
    // Make changes to our team
    team.Name = model.Name;
    team.Sport = model.Sport;
    // For each colour in our team colours but not in our model colours, remove
    foreach (var colour in team.Colours)
        if (!model.Colours.Any(c => c.Id == colour.Id))
            team.Colours.Remove(colour);
    // For each colour that has to be added, add to our team colours
    if (model.Colours != null)
        foreach (var colour in model.Colours)
            if (!team.Colours.Any(c => c.Id == colour.Id))
                team.Colours.Add(colours.Where(m => m.Id == colour.Id).SingleOrDefault());
    // Update the team
    this.service.Update(team);
    // Save our changes
    await this.unitOfWork.SaveChangesAsync();
    // Return Ok
    return Ok(model);
}
But it didn't work. I got an error stating:
Collection was modified; enumeration operation may not execute.
I know it is talking about the Colours but I have no idea how to get around it.
Perhaps someone has had a similar problem and managed to fix it?
 
     
     
    