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) { try { Uri oUri = new Uri("https://yourcrm.crm.dynamics.com/XRMServices/2011/Organization.svc"); ClientCredentials clientCredentials = new ClientCredentials(); clientCredentials.UserName.UserName = "your@email.com"; clientCredentials.UserName.Password = "yourpassword"; OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(oUri, null, clientCredentials, null); _serviceProxy.EnableProxyTypes(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); var accounts = from a in orgContext.CreateQuery("account") select a["name"]; foreach (var name in accounts) { System.Console.WriteLine(name); } Console.WriteLine(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } }
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) { System.Console.WriteLine(account["name"]); }
Which produces:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL