Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Suggested answer

Deleting sales order when an error occurs when saving sales order lines

(1) ShareShare
ReportReport
Posted on by 52
Hi everyone.
 
I use the OData connected services library to create sales orders and sales order lines to Dynamics 365. This works well for the most part. My functionality first saves a sales order, then once that has been saved, it saves its sales order lines. 
 
However, if an error occurs on saving the sales order lines, the sales order lines are obviously not saved, but the sales order has already been saved. I have tried to delete the sales order when there is an error saving the lines, but I was unsuccessful. This is my code: 
 
try
{
// code for creating sales order and sales order lines
}
catch (Exception ex)
{
             try
                {
                    if (salesOrderCreated)
                    {
                        foreach (SalesOrderLine line in salesOrderLineCollection)
                        {
                            d365.DeleteObject(line);
                        }

                        d365.DeleteObject(soh);

                        d365.SaveChanges();
                    }
                }
             catch (Exception e)
             { 
                  throw e; 
             }
}
d365 is the Context of the d365 object of type Resources.
 
Anyone know how I can delete the sales order successfully? With the current implementation, I am getting the following error on saving the changes after deleting soh: 
 
Precondition Failed 
   at Microsoft.OData.Client.SaveResult.HandleResponse() in D:\a\1\s\src\Microsoft.OData.Client\SaveResult.cs:line 347
   at Microsoft.OData.Client.BaseSaveResult.EndRequest() in D:\a\1\s\src\Microsoft.OData.Client\BaseSaveResult.cs:line 304
   at Microsoft.OData.Client.DataServiceContext.SaveChanges(SaveChangesOptions options) in D:\a\1\s\src\Microsoft.OData.Client\DataServiceContext.cs:line 2260
   at Microsoft.OData.Client.DataServiceContext.SaveChanges() in D:\a\1\s\src\Microsoft.OData.Client\DataServiceContext.cs:line 2239
   at myCode.CreateSalesOrder(Resources d365, SalesOrder) in C:\path:line 205


I have tried different ways to resolve this, such as creating a different context and saving using that, or detaching and reattaching the sales order before saving. I was unsuccessful with both these attempt.
 
  • Mar23 Profile Picture
    52 on at
    Deleting sales order when an error occurs when saving sales order lines
    Moreover, I tried following this way of creating sales orders and sales order lines: https://axgenius.blogspot.com/2019/10/create-read-data-using-odata-service-in.html​​​​​​​ to keep the sales order number, but i still get the same error that the precondition failed
     
  • Mar23 Profile Picture
    52 on at
    Deleting sales order when an error occurs when saving sales order lines
    Hi Anthony, 
     
    I tried your suggestion, but now I am getting the below error: Exception has been thrown by the target of an invocation.
     
    Also, when setting details for the sales order lines, I need to set the sales order number, which is generated automatically when creating the sales order itself. 
     
    Full error I am getting after your suggestion: 

    {
      "error":{
        "code":"","message":"An error has occurred.","innererror":{
          "message":"Exception has been thrown by the target of an invocation.","type":"System.Reflection.TargetInvocationException","stacktrace":"   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)\r\n   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataEntityDeserializer.ReadODataBodyAsType(HttpRequestMessage request, Type clrType)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataController.ReadBodyAsDeltaWithRetry(EntityType entityType, Type readType)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataController.Post()\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClassc.<GetExecutor>b__6(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","internalexception":{
            "message":"A null value was found for the property named 'dataAreaId', which has the expected type 'Edm.String[Nullable=False]'. The expected type 'Edm.String[Nullable=False]' does not allow null values.","type":"System.InvalidOperationException","stacktrace":"   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataEntityDeserializer.ReadODataBody[T](HttpRequestMessage request)"
          }
        }
      }
    }
  • Suggested answer
    Anthony Blake Profile Picture
    2,359 Super User 2025 Season 1 on at
    Deleting sales order when an error occurs when saving sales order lines
    Try running the header and lines as a single transaction?
     
     
    The downside will be if any line fails, the whole order will roll back, although this might also be useful to you.


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

🌸 Community Spring Festival 2025 Challenge 🌸

WIN Power Platform Community Conference 2025 tickets!

Jonas ”Jones” Melgaard – Community Spotlight

We are honored to recognize Jonas "Jones" Melgaard as our April 2025…

Kudos to the March Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,261 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 233,011 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Product updates

Dynamics 365 release plans