EF Code First is a simple delete query.

delete-row entity-framework

Question

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.

1
7
3/6/2012 11:20:22 AM

Accepted Answer

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);
4
3/6/2012 11:27:39 AM

Popular Answer

You can use

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

NOTE: The accepted answer does not compile.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow