简体   繁体   中英

Value cannot be null. (Parameter 'key') On Web API POST Method

So Basically I Have Created Add Cars Method In CarsRepository.cs

   public int AddCar(Car car)
        {
            _carRentalSystemContext.Cars.Add(car);
            _carRentalSystemContext.SaveChanges();
            return 1;
        }

In CarsService.cs

   public int AddCar(Car car)
        {
           return _icarsRepository.AddCar(car); 
        }

In Both ICarsRepository And ICarsServices

int AddCar(Car car);

And Action In CarsController As

 [HttpPost]
        [Route("AddCar")]
        public IActionResult AddCar(Car car)
        {
            return new ObjectResult(_icarsService.AddCar(car));
        }

And My Model Class For Car Is

using System;
using System.Collections.Generic;


#nullable disable

namespace CAR_RENTAL_SYSTEM.Models
{
    public partial class Car
    {
        public Car()
        {
            Bookings = new HashSet<Booking>();
            CarReviews = new HashSet<CarReview>();
            DriverReviews = new HashSet<DriverReview>();
        }
        
        public int CarId { get; set; }
        public string CarModel { get; set; }
        public string CarRtoNumber { get; set; }
        public string CarType { get; set; }
        public decimal? CarMileage { get; set; }
        public int? CarPersonCapacity { get; set; }
        public string CarCondition { get; set; }
        public decimal? KmDone { get; set; }
        public string FuelType { get; set; }
        public decimal? RentPerKm { get; set; }
        public string ReviewId { get; set; }
        public string InService { get; set; }

        public virtual ICollection<Booking> Bookings { get; set; }
        public virtual ICollection<CarReview> CarReviews { get; set; }
        public virtual ICollection<DriverReview> DriverReviews { get; set; }
    }
}

The JSON Body Im Sending Through Swagger Is

{
  "carId": 0,
  "carModel": "Audi",
  "carRtoNumber": "MHJK5645",
  "carType": "Sedan",
  "carMileage": 12,
  "carPersonCapacity": 8,
  "carCondition": "Good",
  "kmDone": 15500,
  "fuelType": "Petrol",
  "rentPerKm": 25,
  "reviewId": "MHJK12",
  "inService": "Yes",
  "bookings": [
    {
      "bookingId": 0,
      "customerId": 0,
      "carId": 0,
      "driverId": 0,
      "fromDate": "2022-01-07T14:32:48.971Z",
      "toDate": "2022-01-07T14:32:48.971Z",
      "fromLocation": "string",
      "toLocation": "string",
      "noOfPersons": 0,
      "bookingStatus": "string",
      "journeyCompletion": "string",
      "paymentStatus": "string",
      "createdOn": "2022-01-07T14:32:48.971Z",
      "updatedOn": "2022-01-07T14:32:48.971Z",
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.971Z",
        "updatedOn": "2022-01-07T14:32:48.971Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      },
      "driver": {
        "driverId": 0,
        "driverName": "string",
        "driverLicensenumber": "string",
        "driverEmail": "string",
        "driverPassword": "string",
        "driverPhone": "string",
        "driverAddress": "string",
        "anyAddiction": "string",
        "driverAge": 0,
        "reviewId": "string",
        "inService": "string",
        "isActive": "string",
        "bookings": [
          null
        ],
        "driverReviews": [
          null
        ],
        "journeyCompletions": [
          {
            "journeyId": 0,
            "bookingId": 0,
            "driverId": 0,
            "kmDone": 0,
            "totalFare": 0,
            "receipts": [
              {
                "receiptId": 0,
                "bookingId": 0,
                "journeyId": 0,
                "totalFare": 0,
                "paymentStatus": "string"
              }
            ]
          }
        ]
      },
      "carReviews": [
        {
          "reviewId": 0,
          "carId": 0,
          "customerId": 0,
          "bookingId": 0,
          "review": "string",
          "rating": 0,
          "customer": {
            "customerId": 0,
            "customerName": "string",
            "customerPassword": "string",
            "customerEmail": "string",
            "customerPhone": "string",
            "customerAdress": "string",
            "customerCity": "string",
            "customerPin": 0,
            "createdOn": "2022-01-07T14:32:48.972Z",
            "updatedOn": "2022-01-07T14:32:48.972Z",
            "isActive": "string",
            "bookings": [
              null
            ],
            "carReviews": [
              null
            ],
            "driverReviews": [
              null
            ],
            "feedbacks": [
              {
                "feedbackId": 0,
                "bookingId": 0,
                "customerId": 0,
                "feedbackMsg": "string"
              }
            ]
          }
        }
      ],
      "driverReviews": [
        {
          "reviewId": 0,
          "driverId": 0,
          "customerId": 0,
          "carId": 0,
          "bookingId": 0,
          "review": "string",
          "rating": 0,
          "customer": {
            "customerId": 0,
            "customerName": "string",
            "customerPassword": "string",
            "customerEmail": "string",
            "customerPhone": "string",
            "customerAdress": "string",
            "customerCity": "string",
            "customerPin": 0,
            "createdOn": "2022-01-07T14:32:48.972Z",
            "updatedOn": "2022-01-07T14:32:48.972Z",
            "isActive": "string",
            "bookings": [
              null
            ],
            "carReviews": [
              null
            ],
            "driverReviews": [
              null
            ],
            "feedbacks": [
              {
                "feedbackId": 0,
                "bookingId": 0,
                "customerId": 0,
                "feedbackMsg": "string"
              }
            ]
          },
          "driver": {
            "driverId": 0,
            "driverName": "string",
            "driverLicensenumber": "string",
            "driverEmail": "string",
            "driverPassword": "string",
            "driverPhone": "string",
            "driverAddress": "string",
            "anyAddiction": "string",
            "driverAge": 0,
            "reviewId": "string",
            "inService": "string",
            "isActive": "string",
            "bookings": [
              null
            ],
            "driverReviews": [
              null
            ],
            "journeyCompletions": [
              {
                "journeyId": 0,
                "bookingId": 0,
                "driverId": 0,
                "kmDone": 0,
                "totalFare": 0,
                "receipts": [
                  {
                    "receiptId": 0,
                    "bookingId": 0,
                    "journeyId": 0,
                    "totalFare": 0,
                    "paymentStatus": "string"
                  }
                ]
              }
            ]
          }
        }
      ],
      "feedbacks": [
        {
          "feedbackId": 0,
          "bookingId": 0,
          "customerId": 0,
          "feedbackMsg": "string"
        }
      ],
      "journeyCompletions": [
        {
          "journeyId": 0,
          "bookingId": 0,
          "driverId": 0,
          "kmDone": 0,
          "totalFare": 0,
          "receipts": [
            {
              "receiptId": 0,
              "bookingId": 0,
              "journeyId": 0,
              "totalFare": 0,
              "paymentStatus": "string"
            }
          ]
        }
      ],
      "receipts": [
        {
          "receiptId": 0,
          "bookingId": 0,
          "journeyId": 0,
          "totalFare": 0,
          "paymentStatus": "string"
        }
      ]
    }
  ],
  "carReviews": [
    {
      "reviewId": 0,
      "carId": 0,
      "customerId": 0,
      "bookingId": 0,
      "review": "string",
      "rating": 0,
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.972Z",
        "updatedOn": "2022-01-07T14:32:48.972Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      }
    }
  ],
  "driverReviews": [
    {
      "reviewId": 0,
      "driverId": 0,
      "customerId": 0,
      "carId": 0,
      "bookingId": 0,
      "review": "string",
      "rating": 0,
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.972Z",
        "updatedOn": "2022-01-07T14:32:48.972Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      },
      "driver": {
        "driverId": 0,
        "driverName": "string",
        "driverLicensenumber": "string",
        "driverEmail": "string",
        "driverPassword": "string",
        "driverPhone": "string",
        "driverAddress": "string",
        "anyAddiction": "string",
        "driverAge": 0,
        "reviewId": "string",
        "inService": "string",
        "isActive": "string",
        "bookings": [
          null
        ],
        "driverReviews": [
          null
        ],
        "journeyCompletions": [
          {
            "journeyId": 0,
            "bookingId": 0,
            "driverId": 0,
            "kmDone": 0,
            "totalFare": 0,
            "receipts": [
              {
                "receiptId": 0,
                "bookingId": 0,
                "journeyId": 0,
                "totalFare": 0,
                "paymentStatus": "string"
              }
            ]
          }
        ]
      }
    }
  ]
}

So After Building This Project I Get Build Succeded And In Swagger When I Try To Add A Car Using Respective JSON Body Following Error Occurs

System.ArgumentNullException: Value cannot be null. (Parameter 'key')
   at System.Collections.Generic.Dictionary`2.FindValue(TKey key)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityReferenceMap.TryGet(Object entity, IEntityType entityType, InternalEntityEntry& entry, Boolean throwOnNonUniqueness)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.TryGetEntry(Object entity, IEntityType entityType, Boolean throwOnTypeMismatch)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.InitialFixup(InternalEntityEntry entry, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Add(TEntity entity)
   at CAR_RENTAL_SYSTEM.Repositories.CarsRepository.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Repositories\CarsRepository.cs:line 15
   at CAR_RENTAL_SYSTEM.Services.CarsService.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Services\CarsService.cs:line 16
   at CAR_RENTAL_SYSTEM.Controllers.CarsController.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Controllers\CarsController.cs:line 22
   at lambda_method2(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
   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 ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: close
Content-Length: 5075
Content-Type: application/json
Cookie: ai_user=05ZDd|2021-12-14T10:16:21.921Z; ai_session=zEAqz|1641560256601|1641562776408.5
Host: localhost:44353
Referer: https://localhost:44353/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
origin: https://localhost:44353
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

And I Checked Methods and Model there is no issue project build succeeds & Update Method Works For Same Model But Not Add Method

how to solve this error?

Note:This Project Is Created Using DBFirst With Scaffold Command For Generating Models.

Update: Thanks To AchoVasilev, I Removed Id From Json Body, As It was AutoIncrement In Database, And Also The Error Caused By Default Suggested Request Body By Swagger Contained Reference To Other Tables Also.

What I Did: I Used Insomnia As Rest Client And Called Same API Endpoint With Json Body Without CarID[Which Was Identity] & Removed The Other Table References Which results as:

{
  
  "carModel": "CarNameHere",
  "carRtoNumber": "DL456560",
  "carType": "Sedan",
  "carMileage": 18,
  "carPersonCapacity": 5,
  "carCondition": "Excellent",
  "kmDone": 15000,
  "fuelType": "Petrol",
  "rentPerKm": 20,
  "reviewId": "DL4565",
  "inService": "Yes"
  
 
}

And Sent POST Request And It Has Worked Flawlessely..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM