EF Core和ASP.NET没有将子对象插入数组

时间:2018-04-25 02:18:13

标签: c# entity-framework-core

我来自EF 6,其中将子对象插入父实体的列表中看起来像这样:

[HttpPost, Route("{id:int}")]
public async Task<IActionResult> Post(int id, MenuViewModel menu){
    if (!ModelState.IsValid)
        return BadRequest("Something is wrong with the model");

    var restaurant = await db.Restaurants.Where(r => r.Id == id).Include(r=> r.Menus).FirstOrDefaultAsync();

    if (restaurant == null)
        return BadRequest("That restaurant does not exist");

    var menuModel = Mapper.Map<Menu>(menu);
    restaurant.Menus.Add(menuModel);
    db.Restaurants.Update(restaurant);
    await db.SaveChangesAsync();

    return Ok(Mapper.Map<MenuViewModel>(menuModel));
}

1 个答案:

答案 0 :(得分:0)

尝试将您的孩子添加到db然后保存它应该是工作

[HttpPost, Route("{id:int}")]
public async Task<IActionResult> Post(int id, MenuViewModel menu){
    if (!ModelState.IsValid)
        return BadRequest("Something is wrong with the model");

var restaurant = await db.Restaurants.Where(r => r.Id == id).Include(r=> r.Menus).FirstOrDefaultAsync();

if (restaurant == null)
    return BadRequest("That restaurant does not exist");

var menuModel = Mapper.Map<Menu>(menu);
restaurant.Menus.Add(menuModel);
db.Menus.Add(menuModel); //Add to DBContext
db.Restaurants.Update(restaurant);
await db.SaveChangesAsync();

return Ok(Mapper.Map<MenuViewModel>(menuModel));

}