2

We would like to fetch all contacts data from xdb through code in SXA Sitecore 9.1.1.

Could someone assist for this ?

2 Answers 2

2

Code below should do the trick. It gets contacts from xDB in batches of 200 and adds them to the list. Then returns the list.

public async Task<List<Contact>> GetAllContacts()
{
    var allContacts = new List<Contact>();

    try
    {
        using (var client = SitecoreXConnectClientConfiguration.GetClient())
        {
            var query = client.Contacts;

            var enumerator = await query.GetBatchEnumerator(200);

            while (await enumerator.MoveNext())
            {
                foreach (var contact in enumerator.Current)
                {
                    allContacts.Add(contact);
                }
            }
        }
    }
    catch (XdbExecutionException ex)
    {
        // Handle exception
    }

    return allContacts;
}
0
1

I have updated the code suggested by @Marek for you without async and await:

var allContacts = new List<Contact>();
        using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
        {
            try
            {
                var enumerator = client.Contacts.GetBatchEnumeratorSync(200);
                while (enumerator.MoveNext())
                {
                    foreach (var contact in enumerator.Current)
                    {
                        allContacts.Add(contact);
                    }
                }
            }
            catch (XdbExecutionException ex)
            {
                // Handle exception
            }
        }

For more reference: You can go with the below articles. It provides you both Async and Sync examples.

https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/search-contacts.html

https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/export-all-contact-data.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.