我有這個創建方法:實體框架查找表更新/創建
[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);
}
正如你所看到的,創建一個隊的時候,我需要添加顏色查找表。爲此,我從數據庫中獲取顏色,然後使用作爲模型一部分傳遞的顏色對它們進行過濾。
這告訴實體框架,這些顏色沒有新的實體,所以它只是創造,而不是創造新的顏色在查找表中的參考。
現在我想爲update方法做同樣的事情。
我嘗試這樣做:
[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);
}
但沒有奏效。我得到一個錯誤,說明:
收集被修改;枚舉操作可能不會執行。
我知道它在談論顏色,但我不知道如何解決它。
也許有人有類似的問題,並設法解決它?
你能舉個例子,我不能讓這個去工作 – r3plica
想通了:) – r3plica