Deleting multiple records with Entity Framework using a single LINQ query

后端 未结 2 2041
北恋
北恋 2021-02-20 10:16

I\'m trying to perform a DELETE using LINQ that will generate a single query.

Here\'s how I\'m doing it:

// Northw         


        
相关标签:
2条回答
  • 2021-02-20 10:46

    One way to have a batch delete is setting ON CASCADE DELETE on foreign keys. You need to set CASCADE on relation in designer and Set ON CASCADE DELETE on relation in database.

    To delete Products navigation property from Order EF will do (number of Products properties)+1 statements to database.

    I prefer to do it:

    var order = context.Orders.Include(p=>p.Products).Where(o=>o.Order_ID == 11076);
    
    foreach(Product product in order.Products.ToList())
    {
      context.Entry(product).State = EntityState.Deleted;
    }
    context.Entry(order ).State = EntityState.Deleted;
    context.SaveChanges();
    

    Hope it helps.

    0 讨论(0)
  • 2021-02-20 11:04
    1. Install Entity Framework Extended Library (PM> Install-Package EntityFramework.Extended)

    2. Import EntityFramework.Extensions in your code

    3. Delete records specified by inner query

      context.Orders.Where(o=>o.User_ID == 1).Delete();
      

    Deletes all records inside Orders with userID = 1

    0 讨论(0)
提交回复
热议问题