Dynamics CRM 2011 编程系列(19):插件中的事务

来源:互联网 发布:nginx解析其他网站 编辑:程序博客网 时间:2024/06/01 08:00

    Dynamics CRM 2011中的插件支持事务处理,如果要在插件中执行回滚操作,必须手工的抛出错误。

涉及的实体

 客户

 联系人


需要实现的需求

1.在客户更新的时候创建分别创建一条客户记录和一条联系人记录

2.检查插件的当前执行环境是否包含在事务中,如果包含则抛出错误回滚操作。



实现步骤

图1

图2

图3

图4


使用到的脚本

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Transactions;using Microsoft.Xrm.Sdk;using Microsoft.Xrm.Sdk.Messages;using Microsoft.Xrm.Sdk.Query;namespace Plugin19{    public class TestTransaction : 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 account = new Entity();            account.LogicalName = "account";            account["name"] = "马小虎";            service.Create(account);            //创建联系人            Entity contact = new Entity();            contact.LogicalName = "contact";            contact["lastname"] = "黄小仙";            service.Create(contact);            if (context.IsInTransaction)//是否在事务中            {                throw new InvalidPluginExecutionException("取消创建");            }        }    }}



小结

  虽然弹出窗口有点丑陋,但为了达到事务的效果我们还得接受它呀。