我正在尝试更新帐户实体的所有关联联系人的电话号码。以下是我使用过的代码,
public class Plugin:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity;
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "account") { return; }
}
else
{
return;
}
try
{
string telephoneNum = string.Empty;
IOrganizationServiceFactory serviceFactory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =serviceFactory.CreateOrganizationService(context.UserId);
var id = (Guid)context.OutputParameters["id"];
telephoneNum = entity.GetAttributeValue<string>("telephone1");
UpdateContact(service, id,telephoneNum);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException(
"An error occurred in the plug-in.", ex);
}
}
private static void UpdateContact(IOrganizationService service, Guid id,string telephoneNUm)
{
using (var crm = new XrmServiceContext(service))
{
var res = from c in crm.CreateQuery("contact")
where c["parentcustomerid"].Equals(id)
select c;
foreach (var c in res)
{
Entity e = (Entity)c;
e["telephone1"] = telephoneNUm;
crm.UpdateObject(e);
}
crm.SaveChanges();
}
}
}
我在更新和主要实体“帐户”上注册插件,但每当我在电话字段中更改号码后尝试保存帐户表单时,我会看到弹出错误。我错过了什么吗?谢谢大家!
答案 0 :(得分:0)
只是一个预感......但我认为你是以错误的方式得到了Id ..通过以下方式得到它:
Guid Id = context.PrimaryEntityId
但正如佩德罗建议的那样..你需要看看确切的错误是什么,或者尝试使用附加进程来调试插件..