find and solve ||
Please wait.....

How to Delete multiple records in Linq to Entity

How to Delete multiple records int Linq to Entity?.What is the best way to delete all related rows by linquery?.How to quickly clear a table or What is the best way to delete multiple record in core.We are try to clear about what is the best way to delete all record from database.Delete multiple records using LINQ in C#.


Option 1.

The best way to delete multiple record like as:

context.ExecuteCommand("DELETE FROM <your_entityt_name");

or you can use like that

context.ExecuteCommand("TRUNCATE TABLE <your_entityt_name"");

//this also delete primary key identity but DELETE is not delete idenity number

For some exmple

I have insert tow row and my primary key are 1 and 2 which is increase by IDENTITY(1,1).If i use TRUNCATE  TABLE <Table_Name> and execute this query then insert again one record in the table,the IDENTITY(1,) was start from from 1 but if you use DELETE  FROM <Table_Name> and then  insert one record in the table,the identity(1,1)  number was start from 3.

Option 2.

  public static class LinqExtension{
  public static void Truncate<TEntity>(this Table<TEntity> table) where TEntity : class
    var rowType = table.GetType().GetGenericArguments()[0];
    var tableName = table.Context.Mapping.GetTable(rowType).TableName;
    var sqlCommand = String.Format("TRUNCATE TABLE {0}", tableName);

Option 3.

You can use like that.

DemoConnection ctx = new DemoConnection ("ConnetionString_Name");
var employee= ctx.EmployeeInfo.Where(c => c.Name == "yourReuestName");
ctx.EmployeeInfo.DeleteAllOnSubmit(employee); ctx.SaveChanges();

Option 4.

In the EntityFramework 6.Thi is the best for some condition

// Database context
EntitiesContext _ent = new EntitiesContext(connString);
// Select all the records to be deleted
IEnumerable<entity> list = _ent.entity.where(x=> == id).toList();
// Use Remove Range function to delete all records at once
// Save changes

Option 5.

ExecuteQuery and ExecuteCommand allow you to specify a variable number of arguments for parameter substitution. For example, you can specify the parameters when invoking ExecuteQuery<TResult>:

//open connection like as 
MyConnection con = new Myconnection()
con.ExecuteQuery<Customer>("SELECT * FROM dbo.Customers WHERE City = {0}", "London");


con.ExecuteCommand("UPDATE Products SET QuantityPerUnit = {0} WHERE ProductID = {1}", "24 boxes", 5);

Option 6.

    IEnumerable<StudentFee> studentFeeList = _ent.StudentFee.Where(x => x.StudentId == studentId && x.FiscalYearId==getCurrentFiscalYearId).ToList();

     // Use Remove Range function to delete all records at once
     // Save changes

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials


Report Response