Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading