How to use SavedQuery fetch string to retrieve data in .NET?

Info:

System public views for any entity are stored in DB in one table, entity SavedQuery. These predefined views can be used to retrieve data within JS or C# code.

Advantages:

  • query logic is outside developer code

Disadvantages:

  • developer must make sure that fields are available in query
  • query GUID must be known
  • deleting query affects code execution

Query guid can be taken from AdvancedFind:
SqvedQueryGuid

CrmVersion:

2011 OnPremises

Code:

        private DataCollection<Entity> RetrieveDataBasedOnSavedQuery()
        {
            var queryId = new Guid("95E19C8D-1C63-E311-940E-005056894DD9");

            var savedQuery = organizationService.Retrieve(SavedQuery.EntityLogicalName, queryId, new ColumnSet(new[] { "fetchxml" }));
            var queryFetchXml = savedQuery.ToEntity<SavedQuery>().FetchXml;
            
            const string linkEntityMangerUser = 
                @" <link-entity name='systemuser' to='new_leader' alias='Manager'>
                    <attribute name='internalemailaddress' />
                    <attribute name='firstname' />
                    <attribute name='fullname' />
                    <attribute name='domainname' />
                </link-entity>";

            queryFetchXml = InsertIntoFetchQuery(queryFetchXml, linkEntityMangerUser);
            queryFetchXml = EnsureFetchXmlAttribute(queryFetchXml, "new_leader");

            return organizationService.RetrieveMultiple(new FetchExpression(queryFetchXml)).Entities;
        }

        private string EnsureFetchXmlAttribute(string fetchXml, string attribute)
        {
            var attributeValue = string.Format("<attribute name='{0}' />", attribute);

            if (!fetchXml.Contains(attributeValue))
                fetchXml = InsertIntoFetchQuery(fetchXml, attributeValue);

            return fetchXml;
        }

        private string InsertIntoFetchQuery(string fetchXml, string itemToInsert)
        {
            fetchXml = fetchXml.Insert(fetchXml.IndexOf("</entity>"), itemToInsert);

            return fetchXml;
        }

Have an own opinion?