Improving performance of CRM 2016/Dynamics 365 queries in C#



  • Previous version of Dynamics CRM (2011, 2013 and 2015) used to have a class called CachedOrganizationService, that was part of the Microsoft.Xrm.Client.dll Assembly. The new SDK for 2016 and Dynamics 365 doesn't come with that assembly anymore and the connection classes has been moved to the Microsoft.Xrm.Tooling.Connector.dll assembly. However, this class doesn't come with the CachedOrganizationService, if you had an application that used that class and you want to upgrade the code to work with the latest SDK 2016 Dynamics 365 assemblies you will need to manage the caching manually, here is a sample way you can use to improve the queries performance executed by the RetrieveMultiple method of the IOrganizationService interface that is part of the Microsoft.Xrm.Sdk

    private MemoryCache _objectCache = null;
    public EntityCollection RetrieveMultipleCached(Microsoft.Xrm.Sdk.Query.QueryExpression myQueryExpression)
    {
        EntityCollection entityCol = null;
        ObjectCache cache = MemoryCache.Default;
        if (cache.Contains(myQueryExpression.Serialize()))
        {
            entityCol = (EntityCollection)cache[myQueryExpression.Serialize()];
        }
        else
        {
            Microsoft.Xrm.Tooling.Connector.CrmServiceClient conn = new
    Microsoft.Xrm.Tooling.Connector.CrmServiceClient(ConfigurationManager.ConnectionStrings["Xrm"].ConnectionString);
            crmService = (IOrganizationService)conn.OrganizationServiceProxy;
            entityCol = crmService.RetrieveMultiple(myQueryExpression);
            cache.Add(myQueryExpression.Serialize(), entityCol, DateTime.Now.AddDays(30));
        }
        return entityCol;
    }

    You need to be very careful when you use this method as in the case the data changes frequently this way is not recommended, in case you know something changes in the entity data you can invalidate the cache by using a plugin.

    To invalidate the cache you will need to manually remove the items as follows

    foreach (var element in MemoryCache.Default)
    {
    MemoryCache.Default.Remove(element.Key);
    }

    Other recommendations include making the connection object static so you don't need to create the CrmServiceClient on every request.

    Enjoy!



  • Comments



Add a Comment