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
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With