简体   繁体   English

辅助功能,用于删除/删除所有实体数据,EF

[英]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. 使用EF删除大量数据效率很低。 It first loads all the entities from the database and then deletes them one by one. 它首先从数据库中加载所有实体,然后一个一个地删除它们。

Use raw SQL instead: 改用原始SQL:

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. 它将仅对数据库进行一次调用,并让DB一步完成整个删除操作,这将大大提高效率。 If the tables involved are large it's might be worth using TRUNCATE TABLE instead to gain some performance. 如果所涉及的表很大,则可能值得使用TRUNCATE TABLE来获得一些性能。

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. 我建议在这里使用sql。 The way you are doing it is data intensive since EF loads each of those entities to then delete them. 由于EF会加载这些实体中的每个实体然后将其删除,因此您的处理方式会占用大量数据。 Very expensive. 非常贵。

Just write a sql "delete from CertLevelValues" or trunc the table. 只需编写sql“从CertLevelValues删除”或删节表即可。

Significantly faster especially with a large data set. 特别是对于大型数据集,速度明显更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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