这节我们来看看怎样通过插件来实现实体的CRUD。在日常的开发过程中,往往出现这样一类需求:在创建一条记录时判断是否符合某种条件。如果符合就通过程序对条记录进行增/删/改。实现该类需求的最好方式就是插件。
涉及的实体
客户
商机
需要实现的需求
1.当创建一条客户记录时自动创建一条商机记录,并将该商机与该潜在客户关联起来
2.当客户的名称更改时,自动更新与该客户关联的所有商机的名称
实现方案
1.在客户的create事件上创建一个插件,通过该插件创建商机记录
2.在客户的update事件上创建一个插件,通过该插件更新商机记录
技术分析
上面这些插件均需在如下条件下注册:
Event Pipleline Stage Of Execution:post-operation
Execution:synchronous
实现步骤
图1
图2
图3
图4
使用到的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Xrm; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; namespace Plugin17 { public class CRUD : IPlugin { public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(null); Entity curEntity = (Entity)context.InputParameters["Target"]; string optMode = context.MessageName.ToLower(); if (optMode == "create")//创建事件 { Entity opportunity = new Entity(); opportunity.LogicalName = "opportunity"; opportunity.Attributes.Add("name", curEntity["name"].ToString() + "开启的商机" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); opportunity.Attributes.Add("customerid", new EntityReference("account", curEntity.Id)); service.Create(opportunity); } if (optMode == "update")//更新事件 { QueryExpression query = new QueryExpression(); query.EntityName = "opportunity"; query.ColumnSet = new ColumnSet(new string[] { "opportunityid", "name" }); query.Criteria = new FilterExpression(); ConditionExpression conditionExp = new ConditionExpression(); conditionExp.AttributeName = "customerid"; conditionExp.Operator = ConditionOperator.Equal; conditionExp.Values.Add(curEntity.Id); EntityCollection qResult = service.RetrieveMultiple(query); foreach (Entity tmp in qResult.Entities) { var tmpMatch = Regex.Match(tmp["name"].ToString(), ".+(开启的商机.+)"); if (tmpMatch.Success) { Entity uptEntity = new Entity(); uptEntity.LogicalName = "opportunity"; uptEntity.Attributes.Add("name", curEntity["name"].ToString() + tmpMatch.Groups[1].Value); uptEntity.Id = tmp.Id; service.Update(uptEntity); } } } } } }
代码分析
首先通过context.InputParameters["Target"]获取被操作的对象,然后判断引发该插件的操作类型(create或update)。这里我们使用了QueryExpression类来对“商机”实体进行R操作,与上节用的FetchExpression不同。
工具下载