Search code examples
c#sqldynamics-crmdynamics-365fetchxml

Fetch XML filter on Primary Key without name


I am aware the below condition attribute='primaryKey' is not a valid field, wondering if there is some fetch xml syntax that allows you to filter on the Primary Key without knowing the name of the key?

[TestMethod]
public async System.Threading.Tasks.Task ShoulRetrieveAnyEntity(OrganizationServiceProxy _oragnizationServiceProxy)
{
    var entityName = "account";
    var entityGuid = "7004d3c1-3147-e811-a95e-000d3a10877d";

    string xml = "<fetch distinct='false' version='1.0' output-format='xml-platform' mapping='logical' no-lock='true'>" +
                     "<entity name='" + entityName + "'>" +
                        "<all-attributes />" +
                            "<filter type='and'>" +
                                "<condition attribute='primaryKey' operator='eq' value='{" + entityGuid + "}' />" +
                            "</filter>" +
                        "</entity>" +
                    "</fetch>";

    RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = new FetchExpression(xml) };
    EntityCollection eResults = ((RetrieveMultipleResponse)_oragnizationServiceProxy.Execute(rmRequest)).EntityCollection;
    if (eResults.Entities.Count > 0)
    {
        foreach (KeyValuePair<string, object> attribute in eResults.Entities[0].Attributes)
            {
                Console.WriteLine(attribute.Key + ": " + attribute.Value.ToString());
            }
        }
    }
}

Solution

  • Don't over-complicate it. CRM creates the Primary Key from Entity schema name by appending "id" to it for all entities.

    For ex: account is accountid, opportunity is opportunityid, etc

    string xml = "<fetch distinct='false' version='1.0' output-format='xml-platform' mapping='logical' no-lock='true'>" +
                         "<entity name='" + entityName + "'>" +
                            "<all-attributes />" +
                                "<filter type='and'>" +
                                    "<condition attribute='" + entityName + "id' operator='eq' value='{" + entityGuid + "}' />" +
                                "</filter>" +
                            "</entity>" +
                        "</fetch>";
    

    Still if you want to do it in a generic best practice way - Read this.