Comparteix a través de


Paginar conjuntos de resultados grandes con FetchXML

Puede paginar los resultados de una FetchXML consulta utilizando la cookie de paginación. La cookie de paginación es una característica de rendimiento que hace que la paginación de la aplicación sea más rápida para conjuntos de datos muy extensos. Cuando consulte un conjunto de registros, el resultado contendrá un valor para la cookie de paginación. Para un mejor rendimiento, puede pasar ese valor cuando recupere el siguiente conjunto de registros.

FetchXML y QueryExpression utilizan diferentes formatos para sus cookies de paginación. Si convierte de un formato de consulta a otro sí mediante el mensaje FetchXmlToQueryExpressionRequest o el mensaje QueryExpressionToFetchXmlRequest, se omite el valor de la cookie de paginación. Además, si solicita páginas no consecutivas, se omite el valor de la cookie de paginación.

Cuando utiliza la cookie de paginación con FetchXML, debe codificar XML el valor de la cookie. El siguiente ejemplo muestra cómo se ve la cookie codificada en XML cuando se utiliza la cookie de paginación con FetchXML:

strQueryXML = @"  
<fetch mapping='logical' paging-cookie='&lt;cookie page=&quot;1&quot;&gt;&lt;accountid last=&quot;{E062B974-7F8D-DC11-9048-0003FF27AC3B}&quot; first=&quot;{60B934EF-798D-DC11-9048-0003FF27AC3B}&quot;/&gt;&lt;/cookie&gt;' page='2' count='2'>  
 <entity name='account'>  
  <all-attributes/>  
 </entity>  
</fetch>";  

El siguiente ejemplo muestra cómo utilizar la cookie de paginación con una consulta FetchXML . Para obtener el código de muestra completo, consulte Muestra: usar FetchXML con una cookie de paginación.

// Define the fetch attributes.
// Set the number of records per page to retrieve.
int fetchCount = 3;
// Initialize the page number.
int pageNumber = 1;
// Initialize the number of records.
int recordCount = 0;
// Specify the current paging cookie. For retrieving the first page, 
// pagingCookie should be null.
string pagingCookie = null;

// Create the FetchXml string for retrieving all child accounts to a parent account.
// This fetch query is using 1 placeholder to specify the parent account id 
// for filtering out required accounts. Filter query is optional.
// Fetch query also includes optional order criteria that, in this case, is used 
// to order the results in ascending order on the name data column.
string fetchXml = string.Format(@"<fetch version='1.0' 
                                mapping='logical' 
                                output-format='xml-platform'>
                                <entity name='account'>
                                    <attribute name='name' />
                                    <attribute name='emailaddress1' />
                                    <order attribute='name' descending='false'/>
                                    <filter type='and'>
                            <condition attribute='parentaccountid' 
                                            operator='eq' value='{0}' uiname='' uitype='' />
                                    </filter>
                                </entity>
                            </fetch>",
                                _parentAccountId);

Console.WriteLine("Retrieving data in pages\n"); 
Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

while (true)
{
    // Build fetchXml string with the placeholders.
    string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);

    // Excute the fetch query and get the xml result.
    RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
    {
        Query = new FetchExpression(xml)
    };

    EntityCollection returnCollection = ((RetrieveMultipleResponse)_service.Execute(fetchRequest1)).EntityCollection;
    
    foreach (var c in returnCollection.Entities)
    {
        System.Console.WriteLine("{0}.\t{1}\t\t{2}", ++recordCount, c.Attributes["name"], c.Attributes["emailaddress1"] );
    }                        
    
    // Check for morerecords, if it returns 1.
    if (returnCollection.MoreRecords)
    {
        Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);
        Console.WriteLine("#\tAccount Name\t\t\tEmail Address");
        
        // Increment the page number to retrieve the next page.
        pageNumber++;

        // Set the paging cookie to the paging cookie returned from current results.                            
        pagingCookie = returnCollection.PagingCookie;
    }
    else
    {
        // If no more records in the result nodes, exit the loop.
        break;
    }
}

Este código depende de un método CreateXml estático que se muestra a continuación:

public static string CreateXml(string xml, string cookie, int page, int count)
{
    StringReader stringReader = new StringReader(xml);
    var reader = new XmlTextReader(stringReader);

    // Load document
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);

    XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

    if (cookie != null)
    {
        XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
        pagingAttr.Value = cookie;
        attrs.Append(pagingAttr);
    }

    XmlAttribute pageAttr = doc.CreateAttribute("page");
    pageAttr.Value = System.Convert.ToString(page);
    attrs.Append(pageAttr);

    XmlAttribute countAttr = doc.CreateAttribute("count");
    countAttr.Value = System.Convert.ToString(count);
    attrs.Append(countAttr);

    StringBuilder sb = new StringBuilder(1024);
    StringWriter stringWriter = new StringWriter(sb);

    XmlTextWriter writer = new XmlTextWriter(stringWriter);
    doc.WriteTo(writer);
    writer.Close();

    return sb.ToString();
}

Consulte también

Comportamientos y orden de paginación
Ejemplo: uso FetchXML con una cookie de paginación
Creación de consultas con FetchXML
Operadores de consulta de fecha fiscal y anteriores a fecha y hora en FetchXML
Usando FetchXML
Conjuntos de resultados grandes de página con QueryExpression

Nota

¿Puede indicarnos sus preferencias de idioma de documentación? Realice una breve encuesta. (tenga en cuenta que esta encuesta está en inglés)

La encuesta durará unos siete minutos. No se recopilan datos personales (declaración de privacidad).