Quicktip: Always retrieve primary key with distinct=’true’ fetchxml

FetchXml is great when you quickly want to extract some data. Today, I found a weird behaviour, that is either a bug, or a documented “feature” that I am not aware of.

If you run this code below

            var fetch = @"
            <fetch version='1.0' output-format='xml-platform' mapping='logical' {0} count='1'>
	            <entity name='contact'>
		            <attribute name='fullname'/>
	            </entity>
            </fetch>";

            Console.WriteLine("With Distinct True And Without Id\n--------------------------------");
            var results = crmSvc.OrganizationServiceProxy.RetrieveMultiple(new FetchExpression(string.Format(fetch, "distinct='true'"))).Entities.ToList();
            results.ForEach(x => Console.WriteLine("Id: {0}",x.Id));

            Console.WriteLine("\nWith Distinct True And With Id Field\n--------------------------------");
            results = crmSvc.OrganizationServiceProxy.RetrieveMultiple(new FetchExpression(
            @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' count='1'>
	            <entity name='contact'>
                    <attribute name='contactid'/>
		            <attribute name='fullname'/>
	            </entity>
            </fetch>")).Entities.ToList();
            results.ForEach(x => Console.WriteLine("Id: {0}", x.Id));

            Console.WriteLine("\nWith Distinct False\n--------------------------------");
            results = crmSvc.OrganizationServiceProxy.RetrieveMultiple(new FetchExpression(string.Format(fetch, "distinct='false'"))).Entities.ToList();
            results.ForEach(x => Console.WriteLine("Id: {0}", x.Id));

            Console.WriteLine("\nWithout Distinct\n--------------------------------");
            results = crmSvc.OrganizationServiceProxy.RetrieveMultiple(new FetchExpression(string.Format(fetch, string.Empty))).Entities.ToList();
            results.ForEach(x => Console.WriteLine("Id: {0}", x.Id));

You get this output,

Output

As you can see, if you put distinct=true in your fetchxml, without retrieving the primary key, and iterate through the RetrieveMultiple result, the Id property will be Guid.Empty for all the entities in the EntityCollection.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s