Running a Linq Query with Lambda Expressions in Dynamics 365

Leave a comment

Here we will go through an example of running a LINQ query with Dynamics 365.

First, create a new console app. Add the following assemblies to connect to Dynamics 365:

  • Microsoft.Xrm.Sdk
  • System.ServiceModel

Next, add some code. We will first connect to Dynamics 365 using the Organization Service Proxy. From there, we will call EnableProxyTypes. We can then run our LINQ query, which return the name of all accounts:

using System;
using System.Linq;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;

namespace Carl.Crm.OrgServiceProxy
    class Program
        static void Main(string[] args)
                Uri oUri = new Uri("");
                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.UserName.UserName = "";
                clientCredentials.UserName.Password = "yourpassword";

                OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(oUri, null, clientCredentials, null);

                OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);

                var accounts = from a in orgContext.CreateQuery("account")
                               select a["name"];
                foreach (var name in accounts)

            catch (Exception ex)

Running this, we get:

Note to get all fields, use:

var accounts = from a in orgContext.CreateQuery("account")
 select a;

You can also then run lambda expressions in your query like below:

var accounts = orgContext.CreateQuery("account").AsEnumerable().Where(a => a["name"].ToString().StartsWith("A")).ToList();
 foreach (var account in accounts)

Which produces:



Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube


Leave a Reply

Your email address will not be published. Required fields are marked *