c# - 试图从数据库中删除所有匹配的东西,而不仅仅是 firstordefault

标签 c# asp.net-mvc database

这段代码有效,但它只删除了数据库中的第一个位置。我是 .Net 框架的新手。我知道我正在使用 FirstOrDefault;我不知道如何搜索数据库并删除所有符合要求的实例

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");
}

我想做什么:

我想删除数据库中满足条件的所有实例。

我尝试了什么:

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

  • .全部()。但这返回一个 bool 值

  • .Contains()。还返回了一个 bool 值

最佳答案

您可以使用 Where 而不是 FirstOrDefaultCount() 来检查集合

例子:

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");
}

关于c# - 试图从数据库中删除所有匹配的东西,而不仅仅是 firstordefault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68323256/

相关文章:

c# - 根据不同的元素id设置工具提示

database - 如何为 firestore 创建自动删除机制? (删除时间段后的数据)

php - 托管和本地生产服务器之间的双向 mySQL 数据库同步

c# - 无法连接到 ASP.Net 开发服务器问题

c# - 如何使用 LINQ 在 C# 中更改 IQueryable 字段中的值

asp.net-mvc - 如何优雅地重新附加 Entity Framework 5 POCO 结构并保存它?

asp.net-mvc - 格式化 MVC 模型 TimeSpan 字段

javascript - 基于下拉列表的显示和隐藏asp mvc 5

php - 查询使 2 个得分相等的团队

c# - OnActionExecuting 在标准 asp.NET 中等效吗?