How to identify duplicate records with a plugin in

2019-05-25 13:56发布

I am looking to design some logic inside of my create plugin for the entity 'account'.

What it does is basically check account Names and identifies account names which are duplicates on creation.

So if there is an account Name, Barclays for example, and I try to create this again I'm going to alert the user with an error message that this has been created before and prevents this record from being added.

public void Execute(IServiceProvider serviceProvider)
{
   var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

   if (context.InputParameters.Contains("Target") &&
       context.InputParameters["Target"] is Entity)
   {
      // Obtain the target entity from the input parmameters.
      Entity entity = (Entity)context.InputParameters["Target"];

      if (entity.LogicalName == "account")
      {
         bool x = true;

         if (entity.Attributes.Contains("Name") != recordNamesinCRM)
         {                    
         }
         else 
         {
           throw new InvalidPluginExecutionException("You Cannot Have Duplicate Country Codes!.");
         }          
      } 
   }
}

In the code above I am just using "recordNamesinCRM" as an example but I'm sure there is a built in function or way of comparing on create a new name with the rest in the system or a way of counting reoccurring instances.

2条回答
一纸荒年 Trace。
2楼-- · 2019-05-25 14:05

You can use the RetrieveDuplicatesRequest as per this example here:

    /// <summary>
    /// Checks for duplicate Guid
    /// </summary>
    /// <param name="account"></param>
    /// <returns>First duplicate account id, if any duplicates found, and Guid.Empty if not</returns>
    public Guid DuplicateExists(Account account)
    {
        RetrieveDuplicatesRequest request = new RetrieveDuplicatesRequest();
        request.BusinessEntity = account;
        request.MatchingEntityName = Account.EntityLogicalName;
        request.PagingInfo = new PagingInfo();
        request.PagingInfo.PageNumber = 1;
        request.PagingInfo.Count = 1;

        RetrieveDuplicatesResponse response = (RetrieveDuplicatesResponse)ServiceProxy.Execute(request);
        return response.DuplicateCollection.Entities.Count > 0 ? response.DuplicateCollection.Entities[0].Id : Guid.Empty;
    }

See http://crm-edinburgh.com/2011/08/crm-sdk-using-detect-duplicates-settings-in-code/ for an example.

查看更多
小情绪 Triste *
3楼-- · 2019-05-25 14:08

Are you aware of the built-in duplicate detection?

See following links:

although the links describe the duplicate detection of Dynamics CRM 4, they are still valid for Dynamics CRM 2011

Take a look at the article Run Duplicate Detection in the Dynamics CRM 2011 SDK.

You could either use the optional parameter SuppressDuplicateDetection or you could use the RetrieveDuplicatesRequest, although this will only work for existing records.

查看更多
登录 后发表回答