Best way to delete multiple records in a LINQ query?

后端 未结 10 765
暗喜
暗喜 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<ListOfBadRecords>

    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

    0 讨论(0)
  • 2021-01-07 18:22

    Using entity framework 6

    // Database context
    EntitiesContext db = new EntitiesContext(connString);
    // Select all the records to be deleted
    IEnumerable<entity> list = db.entity.where(x=>x.id == id).toList();
    // Use Remove Range function to delete all records at once
    db.entity.RemoveRange(list);
    // Save changes
    db.SaveChanges();
    
    0 讨论(0)
  • 2021-01-07 18:23

    The good old SPROCs.....

    You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class.

    • How to: Call a Stored Procedure by Using LINQ (Visual Basic)
    • LINQ and Stored Procedures
    0 讨论(0)
  • 2021-01-07 18:23

    maybe its litle late for this answer but today I ran into this demand myself I and I came up with this solution

    CustomerDataContext ctx = new CustomerDataContext("connection string");
    
    ctx.Customers.DeleteAllOnSubmit(ctx.Customers.Where(c => c.Name == "david"));
    
    ctx.SubmitChanges();
    
    0 讨论(0)
提交回复
热议问题