Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 967
jgrewal Avatar asked Dec 05 '25 20:12

jgrewal


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");
}
like image 99
Alexander Avatar answered Dec 08 '25 08:12

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!