EntityFramework按ID过滤列表

时间:2015-04-21 13:20:12

标签: c# linq entity-framework

我有这个功能:

[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

1 个答案:

答案 0 :(得分:2)

好的,我知道这很简单。 我将问题行更改为:

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