Home > Mobile >  Get exception: ArgumentNullException: Value cannot be null. (Parameter 'source') for CRUD
Get exception: ArgumentNullException: Value cannot be null. (Parameter 'source') for CRUD

Time:08-04

I tried to simplify all the layers:

  1. Infrastructure Layer which deals with only the data >> has the Repository classes.
  2. Data Transfer Object Layer
  3. Services Layer which holds all the logic and deals with the infrastructure layer

Main Problem: When I try to do CRUD operation I get 500 status code that I don't understand why I am having it.

private readonly IVehicleRepo _IvehicleRepo;
private readonly IMapper mapper;
private readonly ApplicationDbContext _db;

public VehicleController(IVehicleRepo vehicleRepo, IMapper mapper, ApplicationDbContext db)
{
    _IvehicleRepo = vehicleRepo;
    this.mapper = mapper;
    _db = db;
}

[HttpGet("GetAllVehicles")]
public async Task<IActionResult> GetVehiclesAsync()
{
    //var vehicles = await _IvehicleRepo.GetAllVehicleAsync();
    //return StatusCode(200, vehicles);
    var vehicles = await _db.Vehicles.ToListAsync();
    return Ok(vehicles);

I commented out all the code in the layer and tried to get the data straight from the _db context and still faced the same error.

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new VehiclesFluentApi());
        modelBuilder.ApplyConfiguration(new VehiclesCategoriesFluentApi());

        modelBuilder.Entity<VehicleCategoryEntity>().HasData(new VehicleCategoryEntity { VehicleCategoryId = 1, VehicleCategoryName = "Cars" });
        modelBuilder.Entity<VehicleEntity>().HasData(new VehicleEntity
        {
            VehicleId = 1,
            Vehicle_Category_id = 1,
            Vehicle_Cylinders = "4",
            Vehicle_Description = "nice car",
            Vehicle_Doors = "4",
            Vehicle_Exterior_Color = "black",
            Vehicle_FuelType = "gas",
            Vehicle_Make = "hunda",
            Vehicle_Model = "HR-v",
            Vehicle_Mileage = "1200",
            Vehicle_Price = "20000",
            Vehicle_VinNumber = "1212313",
            Vehicle_Trim = "4",
            Vehicle_Year = "2022",
            Condition ="good",
            IsAvaliable =true
        });
    }


    //Create the dbset for the tables in the db
    public DbSet<VehicleEntity> Vehicles;
    public DbSet<VehicleCategoryEntity> VehicleCategories;
}

Error Message:

ArgumentNullException: Value cannot be null. (Parameter 'source')

    Microsoft.EntityFrameworkCore.Utilities.Check.NotNull<T>(T value, string parameterName)
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsAsyncEnumerable<TSource>(IQueryable<TSource> source)
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
    CarDealerShipWebAPI.Controllers.VehicleController.GetVehiclesAsync() in VehicleController.cs

                var vehicles = await _db.Vehicles.ToListAsync();

Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

CodePudding user response:

Provide the setter and getter to the DbSet properties.

public class ApplicationDbContext : DbContext
{
    ...

    public DbSet<VehicleEntity> Vehicles { get; set; }
    public DbSet<VehicleCategoryEntity> VehicleCategories { get; set; }
}

References

Tutorial: Get started with EF Core in an ASP.NET MVC web app (Section: Create the database context)

  • Related