2017-05-14 87 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

相关问题