Dynamics 365 Data Retrieval: Comprehensive Guide

 

Dynamics 365 Data Retrieval: Comprehensive Guide

Retrieving data effectively in Dynamics 365 (D365) is crucial for custom solutions' performance and scalability. This article explores different methods for data retrieval - QueryExpression, FetchXML, RetrieveMultiple, and direct record retrieval, providing complete sample codes for each scenario and a comparative analysis to help choose the right approach for specific needs.

Scenario 1: Direct Record Retrieval for a Single Record

Retrieving a single record directly is a common requirement. Here's how you can achieve this efficiently in a plugin.

Sample Code

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

public class RetrieveRecordPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        try
        {
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {
                EntityReference entityRef = (EntityReference)context.InputParameters["Target"];
                Entity retrievedEntity = service.Retrieve(entityRef.LogicalName, entityRef.Id, new ColumnSet(true));
                // Use retrievedEntity here
            }
        }
        catch (Exception ex)
        {
            throw new InvalidPluginExecutionException(ex.Message);
        }
    }
}

This code retrieves a single record based on the EntityReference provided in the plugin context, including all attributes of the entity.


RetrieveMultiple is a method that can execute both QueryExpression and FetchXML queries.

Scenario 2: Using QueryExpression to Retrieve Multiple

QueryExpression is an object-oriented way to build queries, offering strong typing and compile-time checks.

Sample Code

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

public class RetrieveMultipleRecordsPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        QueryExpression query = new QueryExpression
        {
            EntityName = "account",
            ColumnSet = new ColumnSet("name", "telephone1", "primarycontactid"),
            Criteria = new FilterExpression
            {
                Conditions =
                {
                    new ConditionExpression("name", ConditionOperator.Equal, "Sample Account")
                }
            }
        };

        EntityCollection results = service.RetrieveMultiple(query);
        // Iterate through the results if needed
    }
}

Scenario 3: Using FetchXML to Retrieve Multiple

FetchXML is suitable for complex queries and can be easily copied from the Advanced Find tool.

Sample Code

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

public class RetrieveMultipleUsingFetchXmlPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        string fetchXml = @"
            <fetch top='50'>
                <entity name='account'>
                    <attribute name='name' />
                    <attribute name='telephone1' />
                    <attribute name='primarycontactid' />
                    <filter type='and'>
                        <condition attribute='name' operator='eq' value='Sample Account' />
                    </filter>
                </entity>
            </fetch>";

        EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchXml));
        // Iterate through the results if needed
    }
}


Comparative Analysis


Both QueryExpression and FetchXML in Dynamics 365 have their use cases, and the choice between them depends on specific needs and scenarios:

  • QueryExpression: It is strongly typed, making it easier to work with in C# code, providing IntelliSense and compile-time checks. This can lead to fewer runtime errors and clearer code. It's generally preferred when writing code within plugins or custom workflow activities due to its strong typing and object-oriented nature.

  • FetchXML: It offers a more flexible and readable format for complex queries, especially those involving aggregates, grouping, and outer joins. FetchXML can be easily copied from the Advanced Find tool within Dynamics 365, making it convenient for complex queries designed within the application. It's also the go-to choice when you need to serialize queries or use them in Web API calls.

Performance

Both methods are optimized for performance in Dynamics 365. The difference in performance is usually negligible for most use cases. However, FetchXML might be slightly less performant due to the need to parse the XML string, but this is generally not significant for typical queries.

Flexibility and Complexity

FetchXML might be preferable for complex queries, especially when they are generated or modified dynamically, or when the query is constructed in the front end or by a tool. FetchXML can be easier to manipulate as a string compared to building a QueryExpression object graph.

Personal Preference and Scenario

Some developers prefer QueryExpression for its strong typing and integration with the .NET environment, while others prefer the textual and somewhat more readable format of FetchXML, especially when queries are shared or constructed outside of the plugin code.

Conclusion

  • Use QueryExpression for most plugin and custom workflow activity development tasks due to its strong typing and ease of use within C#.
  • Consider FetchXML for complex queries, especially those involving advanced features not easily accessible via QueryExpression, or when the query is being dynamically constructed or used within web resources.

Ultimately, the best choice depends on the specific requirements of your project, your personal or team's preference, and the complexity of the queries you need to perform.


No comments:

Post a Comment