다음을 통해 공유


BulkDeleteRequest Class

Definition

Contains the data that's needed to submit a bulk delete job that deletes selected records in bulk. This job runs asynchronously in the background without blocking other activities.

public ref class BulkDeleteRequest sealed : Microsoft::Xrm::Sdk::OrganizationRequest
[System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/crm/2011/Contracts")]
public sealed class BulkDeleteRequest : Microsoft.Xrm.Sdk.OrganizationRequest
[<System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/crm/2011/Contracts")>]
type BulkDeleteRequest = class
    inherit OrganizationRequest
Public NotInheritable Class BulkDeleteRequest
Inherits OrganizationRequest
Inheritance
BulkDeleteRequest
Attributes

Examples

The following example shows how to use this message. For this sample to work correctly, you must be connected to the server to get an IOrganizationService interface instance.

The following BulkDeleteExample method creates a bulk delete system job to delete records for tables specified by the tableLogicalNames where the modifiedon column value is less than the value of the notModifiedAfterDate parameter.

/// <summary>
/// Deletes records for specified tables where the modifiedon date is less than specified value.
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance</param>
/// <param name="tableLogicalNames">List of table logical names</param>
/// <param name="notModifiedAfterDate">Records for the specified tables not modified after this date will be deleted.</param>
/// <returns>The ID for the synchronous job</returns>
static Guid BulkDeleteExample(
      IOrganizationService service,
      List<string> tableLogicalNames,
      DateTime notModifiedAfterDate)
{

      // Create queries for each table
      List<QueryExpression> queries = new();

      foreach (string tableLogicalName in tableLogicalNames)
      {
         QueryExpression query = new(tableLogicalName) { };
         query.Criteria.AddCondition("modifiedon", ConditionOperator.LessThan, notModifiedAfterDate);
         queries.Add(query);
      }

      // Prepare the request
      BulkDeleteRequest request = new()
      {
         QuerySet = queries.ToArray(),
         StartDateTime = DateTime.Now,
         RecurrencePattern = string.Empty,
         SendEmailNotification = false,
         JobName = $"Deleting records not modified since {notModifiedAfterDate}",
         ToRecipients = new List<Guid>().ToArray(),  // Required
         CCRecipients = new List<Guid>().ToArray()   // Required
      };

      // Send the request
      var response = (BulkDeleteResponse)service.Execute(request);

      return response.JobId;

}

After sending the bulk delete request, you can check the progress using a static method like the following CheckBulkDeleteJobStatus method. It will poll the AsyncOperation table every minute for 20 minutes to check the status of the job. When the job is successful, it will retrieve details about the results from the BulkDeleteOperation table.

/// <summary>
/// Checks the status of a system job
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance</param>
/// <param name="jobId">The ID of the system job</param>
static void CheckBulkDeleteJobStatus(IOrganizationService service, Guid jobId)
{
      // Monitor the results
      int testLimit = 20; // ~ 20 minutes
      int count = 0;
      string status = "Error";


      // Poll the system job every minute to determine if it has finished.
      while (count < testLimit)
      {
         Task.Delay(60000).Wait(); // Wait a minute

         //Retrieve the system job
         Entity job = service.Retrieve(
            "asyncoperation",
            jobId,
            new ColumnSet("statecode", "statuscode", "dependencytoken"));

         int stateCode = job.GetAttributeValue<OptionSetValue>("statecode").Value;
         int statuscode = job.GetAttributeValue<OptionSetValue>("statuscode").Value;
         string dependencytoken = job.GetAttributeValue<string>("dependencytoken");

         Console.WriteLine($"dependencytoken: {dependencytoken} statecode:{stateCode}");

         // Capture the status when the system job is completed
         if (stateCode == 3) //Completed
         {
            status = statuscode switch
            {
                  30 => "Success",
                  31 => "Failed",
                  32 => "Cancelled",
                  _ => "Error",
            };
            break;
         }

         count++;
      }

      Console.WriteLine($"BulkDelete system job {status}.");

      switch (status)
      {
         case "Success":
            GetResults();
            break;
         case "Failed":
            Console.WriteLine("The bulk delete job failed");
            break;
         case "Cancelled":
            Console.WriteLine("The bulk delete job was cancelled");
            break;
         case "Error":
            Console.WriteLine($"There was an error processing " +
                  $"the bulk delete operation or it took longer " +
                  $"than {testLimit} minutes.");
            break;

      }

      //Retrieve information about the results
      void GetResults()
      {
         QueryExpression bulkDeleteOperationQuery = new("bulkdeleteoperation")
         {
            ColumnSet = new ColumnSet("successcount", "failurecount")
         };
         bulkDeleteOperationQuery.Criteria.AddCondition(
            attributeName: "asyncoperationid",
            conditionOperator: ConditionOperator.Equal,
            values: jobId);

         EntityCollection bulkOperations = service.RetrieveMultiple(bulkDeleteOperationQuery);
         // Only one record should match
         Entity bulkOperation = bulkOperations.Entities.FirstOrDefault();

         int successcount = bulkOperation.GetAttributeValue<int>("successcount");
         int failurecount = bulkOperation.GetAttributeValue<int>("failurecount");

         Console.WriteLine($"SuccessCount:{successcount} FailureCount:{failurecount}");
      }
}

For complete samples, see Sample: Bulk delete exported records and Sample: Bulk delete records that match common criteria

Remarks

Learn how to delete data in bulk

For the Web API use the BulkDelete action.

Usage

Pass an instance of this class to the Execute(OrganizationRequest) method, which returns an instance of the BulkDeleteResponse class.

Privileges and Access Rights

To perform this action, the caller must have prvBulkDelete privileges and read access rights on the entity records that are specified in the request class. The caller must also have Delete message privileges for the entity types being deleted.

Notes for Callers

By default, a system administrator has the BulkDelete privilege for bulk deletions. Other users must be granted the BulkDelete privilege before they can perform a bulk deletion.

When a record is deleted, all its child records are also deleted. The entire deletion fails if the caller doesn't have delete privileges or access rights to perform bulk deletions for any of these records.

The deletion order of the related records depends on the cascade configuration for each entity relationship. For a description of how actions on a parent record can affect related records, see Configure table relationship cascading behavior.

Constructors

BulkDeleteRequest()

Initializes a new instance of the BulkDeleteRequest class.

Properties

CCRecipients

Gets or sets an array of IDs for the system users (users) who are listed in the Cc box of the email notification. Required.

ExtensionData

Gets or sets the structure that contains extra data. Optional.

(Inherited from OrganizationRequest)
Item[String]

Gets or sets the indexer for the Parameters collection.

(Inherited from OrganizationRequest)
JobName

Gets or sets the name of an asynchronous bulk delete job. Required.

Parameters

Gets or sets the collection of parameters for the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
QuerySet

Gets or sets an array of queries for a bulk delete job. Required.

RecurrencePattern

Gets or sets the recurrence pattern for the bulk delete job. Optional.

RequestId

Gets or sets the ID of the request. Optional.

(Inherited from OrganizationRequest)
RequestName

Gets or sets the name of the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
RunNow

For internal use only.

SendEmailNotification

Gets or sets a value that indicates whether an email notification is sent after the bulk delete job has finished running. Required.

SourceImportId

Gets or sets the ID of the data import job. Optional.

StartDateTime

Gets or sets the start date and time to run a bulk delete job. Optional.

ToRecipients

Gets or sets an array of IDs for the system users (users) who are listed in the To box of an email notification. Required.

Applies to

See also