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

CRM 2013 Plugin: Setting up new relationship on newly created Accounts

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

  1. 当自定义实体 "Contract" 创建时,启动插件。
  2. 合同与报价实体具有“1:1”关系。
  3. 引用与自定义实体 'Property' 有 1:N 关系。
  4. 为 Quote 具有的每个属性创建新的帐户记录。
  5. Link将新建的Account记录到Contract中。 Contract 到 Account 的关系是 1 到 N.

我一切正常,但在使用 #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);

                }

存储新创建账户的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);