How should I remove all elements in a DbSet?

后端 未结 6 988
臣服心动
臣服心动 2020-12-04 21:01

What\'s the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?

6条回答
  •  余生分开走
    2020-12-04 21:13

    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()
    

    提交回复
    热议问题