简体   繁体   中英

Helper function to remove/delete all entity data, EF

In my seed data file, I'm first deleting all entries in a particular entity and then adding new. However I feel like the code for deleting data can be improved (or cleaned).

Currently I'm doing like:

 var oldCertCat = context.CertCategoryValues.ToList();
 oldCertCat.ForEach(cat => context.CertCategoryValues.Remove(cat));

Next entity:

 var oldCertLevel = context.CertLevelValues.ToList();
 oldCertLevel.ForEach(certLevel => context.CertLevelValues.Remove(certLevel));

I'm thinking of creating a helper function like:

void DeleteData("EntityName")
{
    var oldData = context."EntityName".ToList();
    oldData.ForEach(item => context."EntityName".Remove(item));
}

It would be more cleaner this way. Any suggestions?

Deleting a lot of data with EF is very inefficient. It first loads all the entities from the database and then deletes them one by one.

Use raw SQL instead:

void Deletedata(string tableName)
{
  context.Database.ExecuteSqlCommand("DELETE FROM {0}", tableName);
}

It will make just one call to the database and let the DB do the entire deletion in one step which is much more efficient. If the tables involved are large it's might be worth using TRUNCATE TABLE instead to gain some performance.

You can do it with a generic

void DeleteData<T>() where T : class
{
    var oldData = context.Set<T>().ToList();
    oldData.ForEach(item => context.Set<T>().Remove(item));
    context.SaveChanges();
}

You can then call it like:

 DeleteData<User>()

if you want to delete all users then.

I would suggest using sql here. The way you are doing it is data intensive since EF loads each of those entities to then delete them. Very expensive.

Just write a sql "delete from CertLevelValues" or trunc the table.

Significantly faster especially with a large data set.

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