2015-12-14 83 views
1

我已经得到父子关系中的实体类型。使用ExecuteTransactionRequest创建相关实体

由于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当我取回多以来,第四一个不是招”尚未创建(?)?

如果不是,我该如何修改我的代码仍然是一个Execute命令在最后?

回答

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

编辑:我知道我误解了部分问题,但以下内容仍然适用于要创建的新的父记录。将其添加到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前面。