How to Query CRM Using LINQ

By | September 13, 2011

The CRM 2011 SDK allows you to query CRM using LINQ. Using the OrganizationContext object you can run complex queries in a very simple way. This is the code example which shows you how to use this new functionality:

    /// <summary>
    /// Looks for opportunities by name
    /// </summary>
    /// <param name=”name”></param>
    /// <returns>Array of opportunities</returns>
    public static Opportunity[] GetOpportunityByName(string name)
    {
      IOrganizationService orgService = null;
      OrganizationContext orgContext = null;
      Opportunity[] returnOpportunities = null;
      DebugHelpers.TraceHelper(“In.”, MethodInfo.GetCurrentMethod(), RegistryManager.GetRegistryConfiguration<int>
(RegistryManager.CONFIGURATION_MEMBER_PATH, CustomConfigurationSettings.TraceOn) == 0 ? false : true, RegistryManager.GetRegistryConfiguration<string>
(RegistryManager.CONFIGURATION_MEMBER_PATH, CustomConfigurationSettings.BusinessLayerTraceFile), 0);
      try
      {
        orgService = FacadeFactory.GetOrganizationService();
        using (orgContext = new OrganizationContext(orgService))
        {
          var opportunityQuery = from opportunity in orgContext.OpportunitySet
                             where opportunity.Name.Contains(name)
                             select new Opportunity
                             {
                               Name = opportunity.Name,
                               OpportunityId = opportunity.OpportunityId,
                               OriginatingLeadId = opportunity.OriginatingLeadId,
                               OwnerId = opportunity.OwnerId,
                               LogicalName = opportunity.LogicalName
                             };
            returnOpportunities = opportunityQuery.ToArray();
        }
      }
      catch (Exception exception)
      {
        throw new BLException(14, exception);
      }
      DebugHelpers.TraceHelper(“Out.”, MethodInfo.GetCurrentMethod(), RegistryManager.GetRegistryConfiguration<int>
(RegistryManager.CONFIGURATION_MEMBER_PATH, CustomConfigurationSettings.TraceOn) == 0 ? false : true, RegistryManager.GetRegistryConfiguration<string>
(RegistryManager.CONFIGURATION_MEMBER_PATH, CustomConfigurationSettings.BusinessLayerTraceFile), 0);
      return returnOpportunities;
    }
You can also download the CRM prototype solution here which contains this example including unit tests. You can use the unit tests to run this example and see how it works.
This code is implemented in the project QualTech.Crm.BL in the class named OpportunityManager.cs.

Leave a Reply