Best way to delete multiple records in a LINQ query?

后端 未结 10 773
暗喜
暗喜 2021-01-07 17:22

What is the best way to remove multiple records in one go with LINQ?

10条回答
  •  臣服心动
    2021-01-07 18:22

    Removing many records based on single where clause

    context.EntityModel
                .RemoveAll(r => r.property == "propertyEntered");
    

    But you could also Remove records from the database that don't exist in List

    context.EntityModel
                .Where(w => w.propertyID == ID).ToList()
                .RemoveAll(r => !ListOfBadRecords.Any(a => a.anyID == r.propertyID ));
    

    Edit:

    Unsure wich is quicker but you could do the 2nd query with this also

    .RemoveAll(r => !ListOfBadRecords.Select(s=>s.propertyID ).Contains(w.propertyID ))

    Edit2: don't forget context.SaveChanges(); as i did in the first draft

提交回复
热议问题