0

I've created an assembly to use within a workflow in Dynamics 365 v9.

I have a Parent entity with a 1:N parental relationship to my Child entity. I want to create the Parent and Child in the same transaction so that if anything fails the whole thing is rolled back.

The documentation says this is done with the AddRelatedObject method.

var parent = new Parent()
{
    Name = "PARENT"
};

var child = new Child()
{
    Name = "CHILD"
};

crmContext.AddObject(parent);
crmContext.AddRelatedObject(parent, new Relationship("my_relationship"), child);
crmContext.SaveChanges();

The classes for Parent and Child were created with the Early Bound Generator plugin for XrmToolbox and have not been altered.

When I call SaveChanges I get the exception:

Message: An error occured while processing this request.
Inner Message: Cannot find record to be updated

I don't know why this is occurring. The same code works in CRM 2011. If I remove the AddRelatedObject line the parent is created just fine.

Any ideas what I'm doing wrong?

Equalsk
  • 7,954
  • 2
  • 41
  • 67

2 Answers2

1

Quoting from an answer on this question, you might want to give this a shot:

EntityA primaryEntity = new EntityA() { //initialise me... };
EntityB secondaryEntity = new EntityB() { //initialise me... };

context.AddObject(primaryEntity);
context.AddObject(secondaryEntity);

// This is the key part: explicitly link the two entities
context.AddLink(primaryEntity, 
    new Relationship("relationship_name_here"), secondaryEntity);

// commit changes to CRM
context.SaveChanges();
Aron
  • 3,877
  • 3
  • 14
  • 21
  • The `AddRelatedObject` method basically calls those two methods together so this code is equivalent to mine and will throw the exception. – Equalsk Feb 07 '19 at 13:54
0

The issue for me turned out to be a separate workflow connected to the child entity that tries to update the parent entity. It was upset because it assumed there was a parent when there was not.

I put a Check Condition at the start of the workflow to terminate it if there's no parent record which has now solved the error.

I didn't realise that errors caused in other plugins/workflows would bubble up to mine.

For anyone else getting this error I'd check two things:

  • Plugins registered against either parent or child entities
  • Workflows associated to either parent or child entities
Equalsk
  • 7,954
  • 2
  • 41
  • 67