0
過濾列表,我有這樣的功能:的EntityFramework通過ID
[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.Join(model.Colours, c => c.Id, m => m.Id, (c, m) => new Colour { Id = c.Id, Hex = c.Hex, Name = c.Name }).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);
}
如果我運行它,然後進入的EntityFramework新的顏色到數據庫中,而不是引用的顏色。 我知道這是因爲我在我的連接中創建了一個新顏色。 如果我改變我的功能是:
[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;
// 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);
}
,一切工作正常。 即在第二片段唯一改變的是:
team.Colours = colours.Join(model.Colours, c => c.Id, m => m.Id, (c, m) => new Colour { Id = c.Id, Hex = c.Hex, Name = c.Name }).ToList();
成爲
team.Colours = colours;
這是從數據庫中檢索列表。 EntityFramework知道這並沒有改變,所以它只是引用顏色而不是創建新的。 如何讓我的過濾列表執行相同的操作?
乾杯, /r3plica
我會問,你想解決什麼大的問題?我無法從你的「加入」中知道你想做什麼。 – user1477388