Querying an Account using QueryByAttribute, FetchXML and LINQ

Using the late bound method, here is the same query results using QueryByAttribute, FetchXML and LINQ.  For this example, I wrote a simple Console Application in Visual Studio 2012.

  1. Create a new project and choose Console Application template.
  2. In Solution Explorer, expand the References folder and add the Microsoft.Xrm.Sdk.dll and Microsoft.Xrm.Client.dll from the CRM SDK /bin folder
    2015-02-26_21h48_34
  3. Also add the System.Runtime.Serialization Assembly
    2015-02-26_21h50_15
  4. Your References should look similar to this:
    2015-02-26_21h52_07
  5. In the code for Program.cs the using statements need to include the following:
    2015-02-26_21h53_47
  6. Inside the Main method, the CrmConnection class is used to connect to Dynamics CRM.
    2015-02-26_22h04_50
  7. Use the OrganizationService and OrganizationServiceContext classes to setup the service and orgContext objects.
    2015-02-26_22h07_13
  8. Code for the query expression (QueryByAttribute)
    Console.WriteLine(“==QueryByAttribute==”);

    QueryByAttribute qba = new QueryByAttribute(“account”);

    qba.ColumnSet = new ColumnSet(“name”);

    qba.Attributes.AddRange(“name”);

    qba.Values.AddRange(“ACME”);

    EntityCollection ecqba = service.RetrieveMultiple(qba);

    foreach (Entity acct in ecqba.Entities)

    {

    Console.WriteLine(acct.Attributes[“name”]);

    }

  1. Code for LINQCode for FetchXML
    Console.WriteLine(“==FetchXML==”);

    string fetch = @”

    <fetch mapping=’logical’>

    <entity name=’account’>

    <attribute name=’name’/>

    <filter type=’and’>

    <condition attribute=’name’ operator=’eq’ value=’ACME’ />

    </filter>

    </entity>

    </fetch>”;

    EntityCollection ecf = service.RetrieveMultiple(new FetchExpression(fetch));

    foreach (Entity acct in ecf.Entities)

    {

    Console.WriteLine(acct.Attributes[“name”]);

    }

  1. Console.WriteLine(“==LINQ==”);

    var linq = from a in orgContext.CreateQuery(“account”)

    where (a[“name”].Equals(“ACME”))

    select a[“name”];

    foreach (var acct in linq)

    {

    Console.WriteLine(acct);

    }

  2. The output should look like this:

    2015-02-26_22h21_49

One thought on “Querying an Account using QueryByAttribute, FetchXML and LINQ

Leave a comment