apex-enterprise-patterns / fflib-apex-common

Common Apex Library supporting Apex Enterprise Patterns and much more!
BSD 3-Clause "New" or "Revised" License
911 stars 517 forks source link

Relationship is not created if both records are of the same type and are both new #279

Open JoelBrenstrum opened 4 years ago

JoelBrenstrum commented 4 years ago

We're currently using a much older version of fflib (~2014), We upgraded to the latest version and are experiencing this issue.

here is a simple example to repro, you will need to create an additional lookup on account.

fflib_ISObjectUnitOfWork uow = Application.UnitOfWork.newInstance();

Account a = new Account(Name= 'Test');
Account b = new Account(Name = 'Test2');
uow.registerRelationship(a, Account.Primary_Supplier__c,b);
uow.registerNew(a);
uow.registerNew(b);
uow.commitWork();

system.assert(a.Id != null);
system.assert(a.Primary_Supplier__c != null);
System.debug('SUCCESS');

2014 version we get SUCCESS Latest version

"exceptionMessage": "System.AssertException: Assertion Failed",
"exceptionStackTrace": "AnonymousBlock: line 12, column 1"

any ideas or help would be greatly appreciated.

nicholas-getpraxis commented 4 years ago

I've gotten success using multiple UnitOfWorks in your same scenario, i.e. setting relationships on the same object, e.g.

//Create a UnitOfWork to handle the object relationships and dmls
fflib_SObjectUnitOfWork uow = (fflib_SObjectUnitOfWork) Application.UnitOfWork.newInstance(new List<SObjectType>{Account.SObjectType});
fflib_SObjectUnitOfWork uow2 = (fflib_SObjectUnitOfWork) Application.UnitOfWork.newInstance(new List<SObjectType>{Account.SObjectType});

//Create SObjects in memory
Account a = new Account(Name= 'Test');
Account b = new Account(Name = 'Test2');

//insert records
uow.registerNew(b);
uow2.registerNew(a, Account.Primary_Supplier__c,b);
uow.commitWork();
uow2.commitWork();

In scenarios where the SObjectTypes are different, I've been able to use one uow, but in this case, I've had to use multiple (one for each level of the same SObjectType)