What\'s the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?
As the accepted answer only mentions about the method below:
context.Database.ExecuteSqlCommand("delete from MyTable");
and rather gives alternatives to it, I've managed to write a method, which you can use to avoid loading all entities, then looping through them and use ExecuteSqlCommand instead.
Assuming using unit of work, where context is DbContext:
using System.Data.Entity.Core.Objects;
using System.Text.RegularExpressions;
public void DeleteAll()
{
ObjectContext objectContext = ( (IObjectContextAdapter)context ).ObjectContext;
string sql = objectContext.CreateObjectSet().ToTraceString();
Regex regex = new Regex( "FROM (?.*) AS" );
Match match = regex.Match( sql );
string tableName = match.Groups[ "table" ].Value;
context.Database.ExecuteSqlCommand( string.Format( "delete from {0}", tableName ) );
}
First block of code retrievs the table name needed in ExecuteSqlCommand method.
Usage:
using ( var context = new UnitOfWork() )
{
context.MyRepository.DeleteAll();
}
There's no need to call
context.SaveChanges()
- 热议问题