简体   繁体   中英

How to do cascade delete efficiently in Entity Framework

I've been looking for a performant way to do cascade deletes, but haven't been able to. Seems like I have to use .Include() to load any dependencies before passing my IQueryable to RemoveRange() , which takes a long time as it loads up all these entries in memory first.

Is there a way to just directly issue a SQL command using EF to delete the entities in question along with any dependencies?

There are several ways to delete multiple entities:

  • Delete everything manually. This way you have to load them in memory first which you don't want.

  • Configure cascade delete rules so that your database will delete the dependencies for you.

  • You can use third party extensions like this one to delete manually what you want, but there is no roundtrip to the database necessary and nothing needs to be loaded in the context before.

In the case you use UnitOfWork you can execute sql with ExecuteSqlCommandAsync

 public async Task<int> ExecuteCommandAsync(string sqlCommand, params object[] parameters)
        {
            return await this.DataContext.Database.ExecuteSqlCommandAsync(sqlCommand, parameters);
        }

Or if you use context directly

using(var context = new SampleContext())
{
    var commandText = "Delete from MyTable where Id=@id";
    var name = new SqlParameter(@id", 1);


    context.Database.ExecuteSqlCommand(commandText, name);
    context.SaveChanges();
}

example

Using Fluent API to configure entities to turn off cascade delete using the WillCascadeOnDelete()

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOptional<Standard>(s => s.Standard)
            .WithMany()
            .WillCascadeOnDelete(false);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM