CRM 插件执行异常前的操作

CRM plugin execution of operations before Exception

我有一个插件需要创建一堆实体,并使用;

service.Create(Entity);

插件结束时(更新前操作,同步)我有时需要取消保存操作。我知道的唯一方法是抛出异常,但如果我这样做,我的 service.Create(Entity) 不会被执行。

如何强制服务执行插件内部的操作,然后抛出异常取消保存?

编辑:代码是;

var id = service.Create(newEntity);
throw new Exception("Cancelled Save but created the new entity");

如果我抛出异常,则不会创建实体。如果我不抛出异常,实体就会创建。我需要它来创建并抛出异常,以便取消保存操作。

感谢您的指点。

如果IPluginExecutionContext.IsInTransaction == true 那么当抛出异常时,任何已经写入数据库的内容都将被回滚。您可以尝试在预验证阶段注册,有时这在交易之外,但并非总是如此。

请注意,不能保证它始终在交易之外。 SDK 文档非常清楚地说明了这一点 - 因此在任何时候都可能发生将其放入事务中的更新。

https://msdn.microsoft.com/en-us/library/gg327941.aspx#bkmk_DatabaseTransactions:

Plug-ins may or may not execute within the database transaction of the Microsoft Dynamics CRM platform. Whether a plug-in is part of the transaction is dependent on how the message request is processed by the pipeline. You can check if the plug-in is executing in-transaction by reading the IsInTransaction property inherited by IPluginExecutionContext that is passed to the plug-in. If a plug-in is executing in the database transaction and allows an exception to be passed back to the platform, the entire transaction will be rolled back. Stages 20 and 40 are guaranteed to be part of the database transaction while stage 10 may be part of the transaction.

Any registered plug-in that executes during the database transaction and that passes an exception back to the platform cancels the core operation. This results in a rollback of the core operation. In addition, any pre-event or post event registered plug-ins that have not yet executed and any workflow that is triggered by the same event that the plug-in was registered for will not execute.

Nicknow 的回答是正确的,但仍有一些方法可以完成您想要做的事情。

  1. 在您的插件中,不要使用插件上下文中的 OrganizationService。创建您自己的新 OrganizationService 就像您创建控制台应用程序一样。这个新的 OrganizationService 将不受原始 OrganizationService 的事务范围的约束。

  2. 创建一个网络服务来完成这项工作。从您的插件中调用此 Web 服务。 Web 服务将不受原始 OrganizationService 的事务范围的约束。

  3. 使用 ExecuteMultiple。我从未尝试过这个,但有人声称它有效:http://crmtidbits.blogspot.com/2014/02/bypass-plug-in-transaction-to-log.html

希望对您有所帮助!