Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple delete query using EF Code First

Is there any way to accomplsig something simple as this using EF Code First

DELETE FROM Order WHERE OrderDate >= @minOrderDate AND OrderDate >= @maxOrderDate

I have a table of which I would like to delete at least 10.000 records. I think it would be rather inefficient to retrieve all records first before I can delete them using a for-each loop.

like image 652
jhoefnagels Avatar asked Mar 06 '12 11:03

jhoefnagels


People also ask

What is the basic syntax for delete query?

This is the basic syntax for using the DELETE query: DELETE FROM table_name WHERE condition of which row(s) to delete; If you want to delete one row from the table, then you have to specify a condition.

How do I delete a single record?

The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause. DELETE FROM table_name WHERE some_condition; table_name: name of the table some_condition: condition to choose particular record.


2 Answers

You can use

ctx.Database.ExecuteSqlCommand(sqlDeleteStatement,
    new SqlParameter("@minOrderDate", minDate),
    new SqlParameter("@maxOrderDate", maxDate));

NOTE: The accepted answer does not compile.

like image 171
Eric J. Avatar answered Oct 17 '22 22:10

Eric J.


You can always send across raw SQL through your context. _context.Database.SqlQuery(sqlDeleteStatement, parameterList)

string sqlDeleteStatement = "DELETE FROM Order" + 
    "WHERE OrderDate >= @minOrderDate AND OrderDate >= @maxOrderDate";

List<SqlParameter> parameterList = new List<SqlParameter>();

parameterList.Add(new SqlParameter("@minOrderDate", minDate));

parameterList.Add(new SqlParameter("@maxOrderDate", maxDate));

_context.Database.SqlQuery(sqlDeleteStatement, parameterList);
like image 42
bdparrish Avatar answered Oct 17 '22 22:10

bdparrish