CRM 2013插件:在新创建的帐户上建立新关系

时间:2015-08-25 16:32:46

标签: c# entity-framework plugins crm dynamics-crm-2013

我正在为CRM 2013(内部部署)创建一个插件。我的要求是这样的:

  1. 当自定义实体“合同”创建时,触发插件。
  2. 合约与Quote实体有“1:1”的关系。
  3. Quote与自定义实体'Property'有1:N的关系。
  4. 对于Quote的每个属性,创建新的帐户记录。
  5. 将新创建的帐户记录链接到合同。合同与账户的关系为1到N
  6. 我得到了所有工作,但不断遇到#5的问题。由于某种原因,插件会抛出一个错误,即帐户ID不存在。

    这是我的代码:

    foreach ("**Property records found in Quote**")
                    {
    
                        var accountEntity = new Entity();
                        accountEntity = new Entity("account");
                        if (record.Attributes.Contains("name"))
                        {
                            accountEntity["name"] = record.Attributes["propertyname"];
                        }
                        else throw new InvalidPluginExecutionException(OperationStatus.Failed, "New Property Name is needed.");
    
                        service.Create(accountEntity);
    
                        var referenceCollection = new EntityReferenceCollection();
                        var relatedEntity = new EntityReference
                        {
                            Id = record.Id,
                            LogicalName = record.LogicalName
                        };
                        referenceCollection.Add(relatedEntity);
                        //The relationship schema name in CRM you are using to associate the entities. 
                        var relRelationship = new Relationship
                        {
                            SchemaName = "new_new_contract_account"
                        };
    
                        service.Associate("account", ContractId, relRelationship, referenceCollection);
    
                    }
    

1 个答案:

答案 0 :(得分:3)

存储新创建的帐户的 ID

var accountid = service.Create(accountEntity);
必须使用以下属性设置

relatedEntity 对象:

var relatedEntity = new EntityReference
{
   Id =  accountid, /*the newly created account's id*/
   LogicalName = "account"
};

service.Associate 行替换为:

service.Associate("new_contract", ContractId, relRelationship, referenceCollection);