Currently I am using the following post method and it is return error 500 internal server error. System.NullReferenceException: Object reference not set to an instance of an object. at WebApi.Controllers.OrderController.PostOrder(Order order)
public async Task<ActionResult<Order>> PostOrder(Order order)
{
// order table
_context.OrderRequests.Add(order);
// orderitem table
foreach (var item in order.OrderItems)
{
_context.OrderItems.Add(item);
}
await _context.SaveChangesAsync();
return CreatedAtAction("GetOrder", new { id = order.OrderID}, order);
}
What is wrong? How do I submit POST on both tables? Or do I have to create a separate web api controller for OrderItems?
System.NullReferenceException: Object reference not set to an instance of an object. at WebApi.Controllers.OrderController.PostOrder(Order order) in C:\dev\Test\WebApi\Controllers\OrderController.cs:line 91 at lambda_method(Closure , Object ) at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult() at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
500
could be because of a server side issue. Looking at the stacktrace of the exception could provide more information. – Sai Gummaluri