如何使用 crm 2011 sdk 和 XrmServiceContext 创建事务?
在下一个示例中,'new_brand' 是一些自定义实体。我想创建三个品牌。第三个拥有错误的 OwnerID guid。当我调用 SaveChanges() 方法时,会创建两个品牌,但出现异常。如何回滚前两个品牌的创建?
是否可以不使用插件和工作流程?
using (var context = new XrmServiceContext(connection))
{
SystemUser owner = context.SystemUserSet.FirstOrDefault(s => s.Id == new Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"));
// create 3 brands
new_brand b1 = new new_brand();
b1.new_brandidentification = 200;
b1.new_name = "BRAND 200";
b1.OwnerId = owner.ToEntityReference();
context.AddObject(b1);
new_brand b2 = new new_brand();
b2.new_brandidentification = 300;
b2.new_name = "BRAND 300";
b2.OwnerId = owner.ToEntityReference();
context.AddObject(b2);
new_brand b3 = new new_brand();
b3.new_brandidentification = 400;
b3.new_name = "BRAND 400";
b3.OwnerId = new EntityReference(SystemUser.EntityLogicalName, new Guid("00000000-0000-0000-0000-000000000000"));
context.AddObject(b3);
context.SaveChanges();
}
最佳答案
实际上,这在不使用插件的情况下是可能的。
您可以使用 CRM 关系链接来强制交易行为:
EntityA primaryEntity = new EntityA() { //initialise me... };
EntityB secondaryEntity = new EntityB() { //initialise me... };
context.AddObject(primaryEntity);
context.AddObject(secondaryEntity);
// This is the key part: explicitly link the two entities
context.AddLink(primaryEntity,
new Relationship("relationship_name_here"), secondaryEntity);
// commit changes to CRM
context.SaveChanges();
这种方法有一些缺点:
另一种方法可能是考虑使用插件实现命令模式。
这个想法是您在客户端上创建 CRM 对象,将它们序列化并通过自定义实体将它们传递给 CRM。然后在此实体上设置预创建插件以在插件事务范围内反序列化和创建对象。
可以在此处找到描述这两种策略的优秀博客文章:http://crm.davidyack.com/journal/2012/6/26/crm-client-extension-data-access-strategies.html
关于sdk - CRM 2011 SDK 交易,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11028749/