2015-04-21 38 views
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

+0

我会问,你想解决什么大的问题?我无法从你的“加入”中知道你想做什么。 – user1477388

回答

2

好吧,我知道这很简单。 我改变了这个问题行:

// For each colour, Add to our team 
team.Colours = colours.Where(m => model.Colours.Any(c => c.Id == m.Id)).ToList();