首页 > 解决方案 > Deleting large volumes of data from database using .NetCore

问题描述

I am trying to delete over 5000 records from the database using .netCore 2.1. I have the following method which works fine however it takes way too long.

public async Task<bool> deleteAdhocDetails(int[] id)
{
    var status = false;

    for (var x = 0; x < id.Length; x++)
    {
        var existingReward = await _context.AdhocRewardInfo
            .Where(d => d.RowID == id[x])
            .FirstOrDefaultAsync<AdhocRewardInfo>();

        if ((existingReward != null) && (existingReward.HaloRewardCode != null))
        {
            try
            {
                //removing existingReward
                _context.AdhocRewardInfo.Remove(existingReward);
                await _context.SaveChangesAsync();
                status = true;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
    return status;
}            
            

I am currently using EFCore.BulkExtensions for inserting records and it works nicely. I tried using BulkDelete but it didn't seem to make a difference. I also tried to use Z.EntityFramework.Extensions.EFCore but couldn't get that to work too. I should also mention that I am kinda new to this. If someone could please point me in the right direction I would appreciate it. Thanks

In the adhoc.service.ts:

deleteAdhocRecipients(id: number[]): Promise<boolean> {
    return this.http.put<boolean>(this.baseUrl + 'deleteAdhocDetails', id)
      .toPromise();
    }

and in the .ts file:

this.general
  .load(this.aService.deleteAdhocCampaign(this.adhocForm.get('create.id').value))
  .then(
    y => {
      if (deleteArr.length > 0) {
        this.general.load(this.aService.deleteAdhocRecipients(deleteArr))
          .then(
            f => this.router.navigate(['/adhoc-campaign/lookup'])
          );
      } else {
        this.router.navigate(['/adhoc-campaign/lookup']);
      }
    }
  );

标签: c#.net-coreentity-framework-core

解决方案


您可以删除对象的选择,然后只做一个 saveChanges

        public async Task<bool> deleteAdhocDetails((int id, object haloRewardCode)[] id)
        {
            try
            {
                for (var x = 0; x < id.Length; x++)
                {
                    var existingReward = new AdhocRewardInfo() { id = id[x].id, HaloRewardCode = id[x].haloRewardCode };

                    if ((existingReward != null) && (existingReward.HaloRewardCode != null))
                    {
                        //removing existingReward
                       _context.AdhocRewardInfo.Remove(existingReward);
                   }
                }
            }
            catch (Exception e)
            {
                throw;
            }

            await _context.SaveChangesAsync();
            return true;
        }

推荐阅读