How to use LINQ Early Binding and Late Binding in MS CRM

LINQ is Language Integrated Query. In this blog, we will see how to use LINQ(Early Binding and Late Binding) in MS CRM.
 
LINQ operators are: from, join, where, orderBy, select, last, skip and take.
 
LINQ provider for MS CRM does not allow “aggregates” and “group by”
 
We need these clause to construct query.
 
In Late Binding use CreateQuery method:
  1. var query = from c in context.CreateQuery<Contact>()  
  2. select c;  
In Early Binding use generated service context: 
  1. var query = from c in context.ContactSet  
  2. select c;  
1] Late Binding Example
 
Create new console application in visual studio File > New Project > Console Application.
 
Add Microsoft.Xrm.Sdk references.
 
Then add below code to your Program.cs file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.Crm.Sdk.Messages;  
  7. using Microsoft.Xrm.Tooling.Connector;  
  8. using System.Net;  
  9. using System.ServiceModel;  
  10. using Microsoft.Xrm.Sdk;  
  11. using Microsoft.Xrm.Sdk.Client;  
  12. namespace LinqInCRM {  
  13.  class Program {  
  14.   static void Main(string[] args) {  
  15.    string url = "https://yourorg.crm.dynamics.com";  
  16.    string userName = "[email protected]";  
  17.    string password = "*****";  
  18.    string conn = $ @ "    
  19.    Url = {  
  20.     url  
  21.    };  
  22.    AuthType = Office365;  
  23.    UserName = {  
  24.     userName  
  25.    };  
  26.    Password = {  
  27.     password  
  28.    };  
  29.    RequireNewInstance = True ";    
  30.    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;  
  31.    using(var svc = new CrmServiceClient(conn)) {  
  32.     #  
  33.     region LateBinding  
  34.     OrganizationServiceContext orgContext = new OrganizationServiceContext(svc);  
  35.     var query = from c in orgContext.CreateQuery("contact")  
  36.     join a in orgContext.CreateQuery("account")  
  37.     on c["parentcustomerid"] equals a["accountid"]  
  38.     where(String) c["firstname"] == "Benno" ||  
  39.      (String) c["lastname"] == "Kurmann"  
  40.     select new {  
  41.      Contact = new {  
  42.        FirstName = c["firstname"],  
  43.         LastName = c["lastname"]  
  44.       },  
  45.       Account = new {  
  46.        Name = a["name"]  
  47.       }  
  48.     };  
  49.     foreach(var record in query) {  
  50.      Console.WriteLine("Contact Name: {0} {1}",  
  51.       record.Contact.FirstName, record.Contact.LastName);  
  52.      Console.WriteLine("Account Name: {0}",  
  53.       record.Account.Name);  
  54.     }#  
  55.     endregion  
  56.     Console.WriteLine("Press any key to exit.");  
  57.     Console.ReadLine();  
  58.    }  
  59.   }  
  60.  }  
  61. }  
2] Early Binding Example
 
First you need to generate service context using Early Bound Generator plugin in XRM toolbox
  1. Open XRMToolBox
  2. Connect to your organisation
  3. Open plugin Early Bound Generator
  4. In entities section – Entities Whitelist – select entities name that you have to generate service context, in global section set namespace
  5. Change service context name if you want
  6. Click Create All button
  7. Generated file path as below:

    C:\Users\username\AppData\Roaming\MscrmTools\XrmToolBox\Settings\EBG\Actions.cs
    C:\Users\ username\AppData\Roaming\MscrmTools\XrmToolBox\Settings\EBG\OptionSets.cs
    C:\Users\ username\AppData\Roaming\MscrmTools\XrmToolBox\Settings\EBG\Entities.cs
  8. After creating the files copy them into your console application project
  9. Add namespace that you set in global section
  10. Add below code in Program.cs file – In this sample we have retrieve data from CRM and created record in crm 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.Crm.Sdk.Messages;  
  7. using Microsoft.Xrm.Tooling.Connector;  
  8. using System.Net;  
  9. using System.ServiceModel;  
  10. using Microsoft.Xrm.Sdk;  
  11. using Microsoft.Xrm.Sdk.Client;  
  12. using CrmEarlyBound;  
  13. namespace LinqInCRM {  
  14.  class Program {  
  15.   static void Main(string[] args) {  
  16.    string url = "https://yourorg.crm.dynamics.com";  
  17.    string userName = "[email protected]";  
  18.    string password = "*****";  
  19.    string conn = $ @ "    
  20.    Url = {  
  21.     url  
  22.    };  
  23.    AuthType = Office365;  
  24.    UserName = {  
  25.     userName  
  26.    };  
  27.    Password = {  
  28.     password  
  29.    };  
  30.    RequireNewInstance = True ";    
  31.    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;  
  32.    using(var svc = new CrmServiceClient(conn)) {  
  33.     #  
  34.     region EarlyBinding  
  35.     using(var serviceContext = new CrmServiceContext(svc)) {  
  36.      var strLead = from ct in serviceContext.LeadSet  
  37.      orderby ct.FirstName descending  
  38.      where(int) ct.StateCode == 3  
  39.      select new {  
  40.       lead = new {  
  41.        fName = ct.FirstName,  
  42.         lName = ct.LastName,  
  43.         statusValue = (OptionSetValue) ct.StatusCode,  
  44.         statusName = ct.StatusCodeEnum,  
  45.         owner = (EntityReference) ct.OwnerId,  
  46.         descision = (bool) ct.DecisionMaker,  
  47.         amount = (Money) ct.BudgetAmount  
  48.       }  
  49.      };  
  50.      foreach(var row in strLead) {  
  51.       Console.WriteLine("First Name: {0} Last Name: {1} StatusCode: {2} StatusName: {3} OwnerID: {4} Owner: {5} Descision: {6} Money: {7} \n",  
  52.        row.lead.fName, row.lead.lName, row.lead.statusValue.Value, row.lead.statusName.ToString(), row.lead.owner.Id, row.lead.owner.Name,  
  53.        row.lead.descision, row.lead.amount.Value);  
  54.      }  
  55.     }#  
  56.     endregion  
  57.     Console.WriteLine("End of first query\n");#  
  58.     region Create lead  
  59.     Lead lead = new Lead() {  
  60.      FirstName = "Akash",  
  61.       LastName = "Vidhate"  
  62.     };  
  63.     Guid leadid = svc.Create(lead);  
  64.     Console.WriteLine("Lead created lead Guid is: " + leadid);#  
  65.     endregion  
  66.     Console.WriteLine("Press any key to exit.");  
  67.     Console.ReadLine();  
  68.    }  
  69.   }  
  70.  }  
  71. }  
Now you can debug the code check the result.
 
To learn more about LINQ, read Introduction to LINQ.