2013-12-11 73 views
2

我試圖從CRM 2013年獲取所有業務部門

嘗試下面的查詢

 var query = _serviceContext.BusinessUnitSet 
          .Where(b => b.EntityState == 0) 
          .Select(x => new 
             { 
              Name = x.Name, 
              Id = x.Id 
             } 
            ) 
          .ToList(); 

檢索所有業務部門使用此查詢我收到一個錯誤只是說:

{System.ServiceModel.FaultCode} {attributeName} {System.Collections.Generic.SynchronizedReadOnlyCollection<System.ServiceModel.FaultReasonText>} 

當在這個主題上搜索時,我發現有關如何檢索單個業務單元(這似乎與檢索「普通」實體不同)的信息,但不知道如何獲取它們全部(link)。

任何幫助,我將如何檢索所有業務單位將不勝感激。

+0

你沒有得到任何錯誤信息?我假設這是CRM Online?這是在插件上下文中,還是這是一個應用程序訪問CRM以外的SDK? – Daryl

回答

2

我想你想從系統中獲取所有活動的經營單位。所以你必須使用IsDisabled屬性來獲取它們。您使用的屬性EntityState用於跟蹤上下文中的實體狀態,而不是指示CRM中實體的狀態。有關BU實體的更多信息,請參閱BusinessUnit Entity

3

試試這個使用QueryExpression

public class BusinessUnit 
    { 
     public Guid Id { get; set; } 
     public String Name { get; set; } 
    } 


    public void GetAllBusinessUnits(Action<QueryExpression> queryModifier = null) 
    { 

     foreach (BusinessUnit m in RetrieveAllBusinessUnit(this.Service, 1000, queryModifier)) 
     { 

      //Console.WriteLine(m.Name); 
     } 
    } 


    public static IEnumerable<BusinessUnit> RetrieveAllBusinessUnit(IOrganizationService service, int count = 1000, Action<QueryExpression> queryModifier = null) 
    { 

     QueryExpression query = new QueryExpression("businessunit") 
     { 
      ColumnSet = new ColumnSet("businessunitid", "name"), 

      PageInfo = new PagingInfo() 
      { 
       Count = count, 
       PageNumber = 1, 
       PagingCookie = null, 
      } 
     }; 

     if (queryModifier != null) 
     { 
      queryModifier(query); 
     } 

     while (true) 
     { 
      EntityCollection results = service.RetrieveMultiple(query); 

      foreach (Entity e in results.Entities) 
      { 
       yield return new BusinessUnit() 
       { 
        Id = e.GetAttributeValue<Guid>("businessunitid"), 
        Name = e.GetAttributeValue<String>("name") 
       }; 
      } 

      if (results.MoreRecords) 
      { 
       query.PageInfo.PageNumber++; 
       query.PageInfo.PagingCookie = results.PagingCookie; 
      } 
      else 
      { 
       yield break; 
      } 
     } 
    }