What is the best way to remove multiple records in one go with LINQ?
This is what I used, first create an IENumerable object of the table where are the records to be removed are, then just use RemoveRange, and finally just save changes to database. Let's say you want to remove all products from one specific supplier ID on the Products table, this is how you could do that.
IEnumerable ProductsToRemove= db.Products.Where(x => x.SupplierId== Supplierid); db.Products.RemoveRange(ProductsToRemove); db.SaveChanges();
I agree with Khurram, it's much more efficient to do this with a simple stored procedure with LINQ (provided you have sufficient permissions in SQL to do this). I'll augment this with an example.
The stored procedure:
CREATE PROCEDURE [dbo].[RemovePermissionsFromRole]
(
@ROLE_ID int
)
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM [RolePermissions] WHERE [RoleID] = @ROLE_ID;
END
Drag the stored procedure from the database explorer onto the methods pane in your DBML file. Save the file. And in code:
if (Request.QueryString["RoleID"] != null) {
int roleID = Convert.ToInt32(Request.QueryString["RoleID"]);
SETSDataContext context = new SETSDataContext();
context.RemovePermissionsFromRole(roleID);
}
With just Entity Framework I found this to be the tightest code.
db.PreperProperties.RemoveRange(db.PreperProperties.Where(c => c.preperFk == prpr.id));
db.SaveChanges();
To delete records with Linq2Sql
CustomerDataContext ctx = new CustomerDataContext("connection string"); var customers = ctx.Customers.Where(c => c.Name == "david"); ctx.Customers.DeleteAllOnSubmit(customers); ctx.SubmitChanges();
The following is more for LINQ to Entities, but it may help:
Bulk-deleting in LINQ to Entities
Here is How I solved the problem :
try
{
List<MaterialPartSerialNumber> list = db.MaterialPartSerialNumbers.Where(s => s.PartId == PartId && s.InventoryLocationId == NewInventoryLocationId && s.LocationId == LocationId).ToList();
db.MaterialPartSerialNumbers.RemoveRange(list);
db.SaveChanges();
}
catch(Exception ex)
{
string error = ex.Message;
}
First, you can find a list of the items you want to delete.
Then, you can use the function RemoveRange(**list_of_item_to_delete**)
so that it removes each instance in the list present in the database.
According to the MSDN, the method removes a range of elements from the List.
For more information, check it here https://msdn.microsoft.com/en-us/library/y33yd2b5(v=vs.110).aspx