2
votes

I'm creating a plugin for CRM 2013 (on-premise). My requirement is like this:

  1. When a custom entity "Contract" creates, fire the plugin.
  2. Contract has "1:1" relationship with the Quote entity.
  3. Quote has a 1:N relationship with custom entity 'Property'.
  4. For every properties that Quote has, create new Account records.
  5. Link the newly created Account records to the Contract. The relationship Contract to Account is 1 to N.

I got all working however keep getting problems with #5. For some reason the plugin throws an error that Account ID does not exist.

Here's my code:

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

1 Answers

3
votes

store the id of the newly created account:

var accountid = service.Create(accountEntity);

relatedEntity object must be set with the following properties:

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

replace your service.Associate line with:

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