2017-05-14 89 views
0

我需要爲Dynamics CRM Online創建插件,在編輯聯繫人字段後隨機更改公司名稱。 因爲我知道我需要更改parentcustomerid字段,但我不知道如何獲取所有客戶ID,並將其中的一個分配給插件的代碼。Dynamics CRM中更換公司的插件

我的代碼:

public class ContactPlugin: IPlugin 
{ 
    public void Execute(IServiceProvider serviceProvider) 
    { 
     IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 

     if (context.InputParameters.Contains("Target") && 
      context.InputParameters["Target"] is Entity) 
     { 
      Entity entity = (Entity)context.InputParameters["Target"]; 

      if (entity.LogicalName == "contact") 
      { 
       //entity.Attributes.Add("parentcustomerid", GetNewParentCustomerId());    
      } 
     } 
    } 
} 

我怎樣才能做到這一點?

回答

3

首先,寫一個函數從CRM中檢索所有帳戶:

static List<Entity> GetAllAccounts(IOrganizationService service) 
{ 
    var query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet(false) }; 
    var accounts = service.RetrieveMultiple(query).Entities.ToList(); 

    return accounts; 
} 

然後在你的插件類的頂部Random類的實例存儲:

static Random random = new Random(); 

然後寫一個函數可以從列表中檢索隨機項目:

static Entity GetRandomItemFromList(List<Entity> list) 
{ 
    var r = random.Next(list.Count); 
    return list[r]; 
} 

調用func蒸發散先得到所有帳戶,然後選擇一個隨機:

var accounts = GetAllAccounts(service); 
var randomAccount = GetRandomItemFromList(accounts); 

然後randomAccount實體轉換爲EntityReference並賦值給你的聯繫人的parentcustomerid屬性:

entity.Attributes.Add("parentcustomerid", new randomAccount.ToEntityReference()); 

更新聯繫並將值插入數據庫中,使用service.Update(entity)。但是,如果您打算調用Update代碼中的直線距離,我建議這樣只有parentcustomerid屬性在數據庫中更新重新實例聯繫人:

var updatedContact = new Entity { Id = entity.Id, LogicalName = entity.LogicalName }; 
updatedContact.Attributes.Add("parentcustomerid", new randomAccount.ToEntityReference()); 
+0

感謝您的幫助,我做了我想要的。 – AlxZahar

相關問題