web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Plugin to update parent on creation of child records

(0) ShareShare
ReportReport
Posted on by 7,316

Hi,

I am trying to write a plugin where everytime a child record gets created.updated/deleted, the associated parent record should be updated with sum of all child record's amount value.

Here is my plugin(below) which works fine updating the parent record with sum of all the existing child record's amount value except the newly created(about to be) child record's amount value.

Also, child record won't get created and I just get a business process error(no useful information of error).

So, updates the parent record but fails to create child record. What am I doing wrong here? Can anybody please suggest? Thanks for any help!

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 
// Get a reference to the Organization service.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters != null) {
Entity entity = (Entity)context.InputParameters["Target"];

//get the associated parent id 
EntityReference a = (EntityReference)entity.Attributes["new_xxx"];
decimal totalAmount = 0; 
try { 
//fetchxml to get the sum total of expense amount 
string estimatedvalue_sum = string.Format(@"   
     ",
a.Id);
EntityCollection estimatedvalue_sum_result = service.RetrieveMultiple(new FetchExpression(estimatedvalue_sum));
foreach (var c in estimatedvalue_sum_result.Entities)
{ totalAmount = ((Money)((AliasedValue)c["amount_sum"]).Value).Value; }

//updating the field on the aaa 
Entity aaa = new Entity("new_xxx"); 
aaa.Id = a.Id;
aaa.Attributes.Add("new_amount", new Money(totalAmount));
service.Update(aaa);

I have the same question (0)
  • Verified answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Hello,

    Here are couple recommendations:

    1. Always run your plugin in post-mode (in pre-mode your child record is not inserted yet so it's not counted during calculation).

    2. For update/delete there will be no new_xxx field available in target so you should master usage of "Pre-Images" in plugins - there are multiple articles available online. You will be able to look it up using search engines.

    3. To avoid performance issues I would recommend to switch your plugins to run asynchronously.

    4. During "delete" scenario Target is actually EntityReference so your code Entity entity = (Entity)context.InputParameters["Target"]; will throw an exception so you will have to rewrite it.

  • DhananjaySharma Profile Picture
    65 on at

    Hi

    You can also use Tracing service to log the error. Enable the Trace log.

    By using trace log you can find excite where is an issue.

    Thanks,

    Dhananjay Sharma

  • Suggested answer
    Charles Abi Khirs Profile Picture
    3,569 on at

    Hello,

    What I suggest is a No-Code solution using Rollup field on the parent entity where you calculate the sum of the amount value of the children records.

    The calculation will take into consideration when a child recod is created/deleted/amount field updated and reflect you need on the parent record.

    The downside of it, is that the calculation will be automatically done each 12 hours; however, you can always click on the refresh button of the parent record field in order to force reclaculate the value immediately.

  • meenoo Profile Picture
    7,316 on at

    I tried that, but my amount field is a simple currency field data type and I couldn't create a rollup field with it!

    Thanks for the suggestion, Charles Abi Khirs. Any work around that you can think of?

  • Charles Abi Khirs Profile Picture
    3,569 on at

    You can create a new Rollup field in order to do it other than the one you have.

    However, I have two questions:

    1. Is the field exist in UAT/PROD environments?

    2. Is the field contain data?

  • meenoo Profile Picture
    7,316 on at

    Yes, its in PROD. We were originally onprem and had placed simple currency field before calculated fields were introduced, now we moved on to cloud. Yes, field has data.

  • Suggested answer
    Charles Abi Khirs Profile Picture
    3,569 on at

    In that case, writing plugins is the best option to go with.

    What is the error you are facing?

  • Charles Abi Khirs Profile Picture
    3,569 on at

    In that case, writing plugins is the best option to go with.

    What is the error you are facing?

  • meenoo Profile Picture
    7,316 on at

    I am getting a generic error when creating the child record. So, the plugin is set to trigger on create of child record(Post Operation) and update the parent record with sum of all the amounts on child records(multiple records associated to parent record).

    It does update the parent record with sum of all the child records amounts except the one I am about to create. So, the total amount on parent record is wrong. And the child record won't get saved. It throws this error.

      at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)

      at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)

      at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)

      at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)

      at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)

      at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)

      at lambda_method(Closure , Object , Object[] )

      at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)

      at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

    Activity Id: 31b11e91-0240-4e25-af95-22419d1e08a1

    I did debug and everything goes through fine without any errors! Makes sense? what is going wrong here?

    Thanks.

  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Hello,

    Did you modify your code comparing to initial version?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 108 Super User 2025 Season 2

#2
Jimmy Passeti Profile Picture

Jimmy Passeti 50 Most Valuable Professional

#3
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 49 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans