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


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.


  • query logic is outside developer code


  • 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:


2011 OnPremises


        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' />

            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?