trying to remove everything that matches from the database not just firstordefault

Viewed 30

this code works but it only removed the first location in the database. I'm fairly new to .Net framework. I understand I'm using FirstOrDefault; I don't know how to search through the database and remove all instances that match the requirements

MMLeagueParticipant removeThisParticipant = db.ParticipatingKids.FirstOrDefault(i=>i.ParticipantId == ParticipantId && i.sport.sport == SportsTab);
if(removeThisParticipant == null)
{
    Console.WriteLine("removeThisParticopant in [IActionResults Remove] was null");
    return RedirectToAction("Dashboard","Dashboard");
}
if(removeThisParticipant != null)
{
    Console.WriteLine("removeThisParticopant in [IActionResults Remove] was NOT null");
    db.ParticipatingKids.Remove(removeThisParticipant);
    db.SaveChanges();
    return RedirectToAction("Dashboard", "Dashboard");
}

What im trying to do:

I want to remove all instances in the database where the conditions are met.

What I tried:

  • .Where() Cannot implicitly convert type 'System.Linq.IQueryable<LeagueProject.Models.MMLeagueParticipant>' to 'LeagueProject.Models.MMLeagueParticipant'.

  • .All(). but this returns a boolean

  • .Contains(). Also returned a boolean

1 Answers

You can use Where instead of FirstOrDefault and Count() to check collection

Example:

IEnumerable<MMLeagueParticipant> removeThisParticipant = db.ParticipatingKids.Where(i=>i.ParticipantId == ParticipantId && i.sport.sport == SportsTab);
if (removeThisParticipant.Count() != 0)
{
     Console.WriteLine("removeThisParticopant in [IActionResults Remove] was NOT null");
     db.ParticipatingKids.RemoveRange(removeThisParticipant);
     db.SaveChanges();
     return RedirectToAction("Dashboard", "Dashboard");   
}
else 
{
    Console.WriteLine("removeThisParticopant in [IActionResults Remove] was null");
    return RedirectToAction("Dashboard","Dashboard");
}
Related