Home > Mobile >  .NET and Entity Framework : delete items from list when posting empty list
.NET and Entity Framework : delete items from list when posting empty list

Time:08-03

I've built an API for a project of mine. Now when I put an empty list in p.Stages, the items don't get removed from the database. If I remember correctly there is some sort of option I need to set but I can't remember which one.

   [HttpPut]
   [Route("EditProject/{projectId}")]
   public async Task<ActionResult> EditProject(Guid projectId, [FromBody] Project p)
   {
        var user = await _userManager.GetUserAsync(HttpContext.User);
        var project = await _dbContext.Projects
                                      .Where(x => x.Id == projectId)
                                      .FirstOrDefaultAsync();

        if (project != null)
        {
            project.Title = p.Title;
            project.Budget = p.Budget;
            project.TimeFrame = p.TimeFrame;
            project.Stages = p.Stages;

            await _dbContext.SaveChangesAsync();

            return Ok(project.Id);
        }

        return NotFound();
    }

So my question is, how can I delete the items from project.Stages when putting an empty list in p.Stages?

CodePudding user response:

I think you have to use Include on your Query

var project = await _dbContext.Projects
                                  .Include(p => p.Stages)
                                  .Where(x => x.Id == projectId)
                                  .FirstOrDefaultAsync();

Entity framework will track it and if you change to empty, It should be remove from database

  • Related