MS CRM2011 PlugIn中 建立和删除关系
此PlugIn 是update的时候执行的
// 获取执行上下文
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// InputParameters属性包含所有输入参数数据
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// 从输入参数中获取Target参数
Entity entity = (Entity)context.InputParameters["Target"];
//检测输入的Target参数,判断其逻辑名称是否是该实体.
if (entity.LogicalName == "crm_media_articles")
{
try
{
if (entity.Attributes.Contains("crm_media_articlesid"))
{
Guid regardingobjectid = new Guid(entity.Attributes["crm_media_articlesid"].ToString());
//创建SERVICE
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
//渠道和媒体稿件关系
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
Relationship relationship = new Relationship("crm_crm_media_articles_crm_channel");//关系名
//查询原来的关系
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "crm_media_articlesid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(regardingobjectid);
FilterExpression filter1 = new FilterExpression();
filter1.Conditions.Add(condition1);
QueryExpression query = new QueryExpression();
query.EntityName = "crm_crm_media_articles_crm_channel";//关系实体名
query.ColumnSet = new ColumnSet("crm_media_articlesid", "crm_channelid");
query.Criteria.AddFilter(filter1);
EntityCollection entitys = _service.RetrieveMultiple(query);//查询存在的关系实体
//删除原来的关系
foreach (var a in entitys.Entities)
{
Guid channelid = new Guid(a.Attributes["crm_channelid"].ToString());
relatedEntities.Add(new EntityReference("crm_channel", channelid));
}
if (relatedEntities.Count > 0)
{
_service.Disassociate(entity.LogicalName, regardingobjectid, relationship, relatedEntities);
}
if (entity.Attributes.Contains("crm_affect_channel_content"))
{
//解析XML字段
string channelXml = entity.Attributes["crm_affect_channel_content"].ToString();
if (!String.IsNullOrEmpty(channelXml))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(channelXml);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("li");
relatedEntities.Clear();
for (var i = 0; i < nodeList.Count; i++)
{
Guid channelid = new Guid(nodeList[i].Attributes["oid"].Value);
relatedEntities.Add(new EntityReference("crm_channel", channelid));
}
//创建新的关系
_service.Associate(entity.LogicalName, regardingobjectid, relationship, relatedEntities);
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}