Reputation: 6613
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?
Upvotes: 1
Views: 867
Reputation: 1762
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.
Upvotes: 1
Reputation: 69270
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.
Upvotes: 5
Reputation: 362
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.
Upvotes: 1