Search code examples
pluginsdynamics-crm-2011dynamics-crmcrmdynamics-crm-2013

How to Detect Duplicate record in CRM 2013 on Create (Pre-Validate ) Plugin


I am writing a plugin which will detect duplicate ID on Create and will restrict the user to enter a new ID instead. NOTE : I CANT USE DEFAULT DUPLICATION METHODS PROVIDED BY MICROSOFT DYNAMICS 2013 or 2015. THIS IS A SPECIAL CASE. Following is the code of my plugin :

enter code here

if (entity.LogicalName == "new_studentinformation")
                {
                    // An accountnumber attribute should not already exist because
                    // it is system generated.
                    if (entity.Attributes.Contains("new_studentid") == false)
                    {
                        // Create a new accountnumber attribute, set its value, and add
                        // the attribute to the entity's attribute collection.
                        Random rndgen = new Random();
                        entity.Attributes.Add("new_studentid", rndgen.Next().ToString());
                    }

Now the problem i am facing is in this line

if (entity.Attributes.Contains("new_studentid") == "Something")

how i can get the value entered by user in crm and compare it to my existing records ?


Solution

  • You need to retrieve the entity from the plugin context as described in the documentation:

    IPluginExecutionContext context = (IPluginExecutionContext)
    serviceProvider.GetService(typeof(IPluginExecutionContext));
    // The InputParameters collection contains all the data passed in the message request.
    if (context.InputParameters.Contains("Target") &&
        context.InputParameters["Target"] is Entity)
    {
        // Obtain the target entity from the input parameters.
        Entity entity = (Entity)context.InputParameters["Target"];
        // Your code here...
        var desiredValue = entity.GetAttributeValue<desiredtype>("desiredfield");
    }