Deleting multiple records with Entity Framework using a single LINQ query

后端 未结 2 2042
北恋
北恋 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.

提交回复
热议问题