CRM Crate

How to retrieve multiple records in plugin using Query Expression

We will learn how to retrieve or fetch multiple records in plugin using Query Expression. While performing operations in plugins, there can be scenarios where you will need to retrieve an entity record from various entities other the the target entity, we can achieve this retrieval of record with help of Query Expressions.

plugin using Query Expression

Before we start, go through the below links to have knowledge of developing and registering the plugins

What is Query Expression?

Query Expression is a class used to build queries in Microsoft Dynamics CRM. It provides an object model to construct a query. Click here to more about the Query Expression class.

Understanding a scenario for using Query Expression

Lets first create an imaginary scenario in which we would be needing a Query Expression. Consider our plugin is getting triggered on creation of Account record with a dedicated value in its field “Account Number” and as part of the business logic we would need to retrieve all Account records with the same Account Number as that of the newly created Account. In order fulfill this requirement we will write a Query Expression in Create event of Account entity.

Writing a Query Expression in Plugin

Before writing a plugin, make sure you are referencing the namespace Microsoft.Xrm.Sdk.Query which is by default found in assembly Microsoft.Xrm.Sdk.dll.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace CRM_Crate___My_Sample_Plugin
{
    public class Plugin : IPlugin
    {

        //Main Execute Method.
        public void Execute(IServiceProvider serviceProvider)
        {

            //Initializing Service Context.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            try
            {

                //Defining Entity Object.
                Entity eTarget = null;
                if (context.MessageName == "Create")
                {

                    //Retrieving Target Entity.
                    eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ?
                    context.InputParameters["Target"] as Entity : null;

                    //Triggering The Logic If Target Is Not Null.
                    if (eTarget != null)
                    {

                        //Stage 1.
                        QueryExpression qeAccount = new QueryExpression("account");

                        //Stage 2.
                        qeAccount.ColumnSet.AddColumns("accountnumber", "accountname", "accountid");

                        //Stage 3.
                        FilterExpression filter = new FilterExpression(LogicalOperator.And);
                        filter.AddCondition("accountnumber", ConditionOperator.Equal, eTarget.GetAttributeValue("accountnumber"));
                        filter.AddCondition("accountname", ConditionOperator.NotNull);
                        qeAccount.Criteria.AddFilter(filter);

                        //Stage 4.
                        EntityCollection entityCollection = service.RetrieveMultiple(qeAccount);

                        if (entityCollection.Entities.Count == 0)
                        {
                            // No Account Found With Similar Account Number.
                        }
                        else
                        {

                            //Stage 5. 
                            int TotalAccountCount = entityCollection.Entities.Count;

                            //Account Records Found With Similar Account Number.
                            foreach (var entity in entityCollection.Entities)
                            {

                                //Stage 6.
                                Entity eAccountNew = new Entity("account");
                                eAccountNew.Id = entity.Id;

                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
    }
}

Explanation of above plugin code

  • Stage 1 : Create a object “qeAccount” of QueryExpression.
  • Stage 2 : Add fields or columns which you want to use and consume in the retrieved Account record. For example, we have given Account Name, Account Number and Account ID columns in the query.
  • Stage 3 : Add filter condition so that we can retrieve specific account records which are matching to our filtering requirement. In our case, we have retrieving Account records which are having same Account Number as that of target Account record and having valid non empty value in its field Account Name. For achieving this operation, we have used Filter Expression within the Query Expression.
  • Stage 4 : Sending RetrieveMultiple request and storing the list of retrieved entities in an entity collection.
  • Stage 5 : Here, we get the total number of Accounts with similar Account Number as that of target.
  • Stage 6 : We have now performed a For-Loop on all retrieved Account records. Here we get each retrieved Account record inside variable “entity” and we can perform the plugin operation on this retrieved Account entity as per the business need.

Thus, we have learned how to query or retrieve records in plugins with help of Query Expression.

CRM Crate

All In One Platform For Learning Microsoft CRM.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
5 1 vote
Article Rating
Subscribe
Notify of
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Understanding plugin images in Microsoft Dynamics CRM - CRM Crate
1 year ago

[…] Retrieving records within CRM by using plugins. […]

Difference between Synchronous & Asynchronous plugins - CRM Crate
1 year ago

[…] Retrieving records using a plugin […]

error: CRM Crate Security Engine - Disabled Right Click & Selection!

Congratulations!

Well Done,
Welcome to CRM Crate

Stay tuned with us and get all latest updates and learning in Microsoft CRM and related techonologes.

Practise EXams

Free!!

Sharpen your skills with our free practise exams.