使用ExecuteTransactionRequest创建相关实体

时间:2015-12-14 20:30:54

标签: c# dynamics-crm

我有父子关系中的实体类型。

由于ExecuteTransactionRequest一个 tranasaction中执行多个邮件请求,以下工作是否会按照我的意图进行?

有3位父母没有孩子可以入手:

//Create a 4th parent
cs_parent parent4 = new cs_parent{ cs_name = "p4" };
CreateRequest createParentRequest = new CreateRequest { Target = parent4 };
request.Requests.Add(createParentRequest);

EntityCollection parents 
  = context.RetrieveMultiple(/*fetchExpression to get all parents (I'm expecting 4 now)*/);

//Create a child for each parent
foreach (var p in parents.Entities)
{
  cs_child child = new cs_child
  {
    cs_parentid = p.ToEntityReference();
  }
  CreateRequest createChildRequest = new CreateRequest { Target = child };
  request.Requests.Add(createChildRequest);
}
response = (ExecuteTransactionResponse)context.Execute(request);

我是否会有4个父母,每个孩子一个孩子,或者只有3个,因为当我检索多个时,第4个尚未创建(?)?

如果没有,我如何在最后使用一个 Execute命令理想地修改我的代码?

2 个答案:

答案 0 :(得分:1)

我实际上并没有为自己运行你的代码以100%肯定,但看起来它会出错,因为第四个父记录没有必要的信息当您在子实体上将其指定为EntityReference时。你可以轻松地解决这个问题。 CRM允许这种类型的情况,其中相互依赖的记录都可以在一个批Create个请求中提交。通常,当您在CRM中创建记录时,系统会为其分配一个唯一标识符(guid),但您可以通过自己分配guid来覆盖它,然后您就可以将其设置为EntityReference在其他地方对象。因此,当您创建第四个父级时,您将拥有以下内容:

cs_parent parent4 = new cs_parent { cs_name = "p4",cs_parentId = Guid.NewGuid());

只是猜测你实体的Id字段,但你明白了。

我不确定您的代码示例中有哪些内容context是什么,所以我无法确定是否对其执行检索将返回您的parent4对象。您可能需要有两个循环,一个用于现有cs_parent记录,以便为它们创建子记录,另一个循环用于为request.Requests列表中尚未包含在系统中的父记录创建子记录。 ......深思熟虑。

答案 1 :(得分:1)

编辑:我意识到我误读了部分问题,但以下内容仍然适用于您要创建的父记录。将其添加到ExecuteTransactionRequest请求。

将子项添加到父Entity's RelatedEntities集合(伪示例):

// Create parent object
var invoice = new Entity("invoice");
// Create list of child objects
var invoiceDetailList = new List<Entity>() { new Entity("invoicedetail"), new Entity("invoicedetail") };
// Add child records to parent record's RelatedEntities
invoice.RelatedEntities.Add(new Relationship("invoice_invoicedetails"), new EntityCollection(invoiceDetailList));
// Add to ExecuteTransactionRequest.
transactionRequest.Requests.Add(new CreateRequest { Target = invoice });

这样您就不需要事先了解父记录的GUID。