简体   繁体   中英

What is the proper way to delete all records in an Entity Framework context and recreate it?

I am looking to keep a database with records of the image paths in the filesystem. It seems like the best way to refresh the records is to delete all the records, then create it all again. As it takes about 1 minute for every 5000 records at which time the images may be unavailable to the web server, I imagine there is a way to do this where it takes less than 1 minute for 5000 records. What would that way be?

Here is an example of slow code:

foreach(ImageRecord imageRecord in EntityFrameworkCollection)
{
    databaseContext.ImageRecords.Remove(imageRecord);
}

//...SaveChanges() and/or recreate context

foreach(ImageRecord imageRecord in FileSystemCollection)
{
    databaseContext.ImageRecords.Add(imageRecord);
}

There is a library called EntityFrameworkPlus that I like using for bulk operations as yours. You can use a DeleteAsync batch operation like so:

await databaseContext.ImageRecords.DeleteAsync();

It will delete all your records without having to go through every records. Fast. Easy.

Then, for adding in batch, you could use the AddRangeAsync method, without having to go through every record, like so:

await databaseContext.ImageRecords.AddRangeAsync(FileSystemCollection);
await databaseContext.SaveChangesAsync();

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