Search code examples
c#.net-coredynamics-crmmicrosoft-dynamics

How to get entity from dynamics 365 using service client by attribute?


I want to get entities by given attribute. ServiceClient.Retrieve method requires Id but I want to use attributes for this. Any suggestions?


Solution

  • In Dynamics 365 there is a QueryByAttribute method (documentation https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/use-querybyattribute-class) however it is rarely used and has limitations.

    You should use QueryExpression (documentation https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/use-queryexpression-class). The documentation example can be simplified, for example if there is only a single condition with AND condition (the default) the code would be:

    QueryExpression query = new QueryExpression("contact");
    query.ColumnSet = new ColumnSet("firstname", "lastname");
    query.Criteria.AddCondition("lastname", ConditionOperator.Equal, "Brown");
    EntityCollection result = service.RetrieveMultiple(query);
    

    For more complex queries you will need to set the FilterExpression.

    There are some tools that can assist you building the queries, for example FetchXML Builder (XrmToolBox tool) can generate C# QueryExpression from the FetchXML that you can build using the tool.

    NOTE: QueryExpression returns max 5000 records, if you need to retrieve more than 5000 records, paging needs to be used.