Search code examples
c#asp.net-coreexception.net-6.0argumentnullexception

ASP.NET .NET6 System.ArgumentNullException: "Value cannot be null. Arg_ParamName_Name"


I have a TryGetByStatementId method, which, using the FirstOrDefault method, returns me the id from the database.

I also have a database that stores information about the uploaded file. I upload the file through the controller, the file is saved in the file system in wwwroot, and information about it such as id, Name, CreateDateTime are saved in the database. When I try to delete information using the TryGetByStatementId method, I get an error -> System.ArgumentNullException: "Value cannot be null. Arg_ParamName_Name"

The controller with which I download the file and save it to the file system

public class ManagementController : Controller
{
    private readonly ApplicationDbContext applicationDb;
    private readonly IWebHostEnvironment _webHostEnvironment;

    public ManagementController(ApplicationDbContext applicationDb, IWebHostEnvironment webHostEnvironment)
    {
        this.applicationDb = applicationDb;
        _webHostEnvironment = webHostEnvironment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> AddFile(IFormFile uploadFile)
    {
        if (uploadFile != null) 
        {
            string path = "/Files/" + uploadFile.FileName;

            using (var fileStream = new FileStream(_webHostEnvironment.WebRootPath + path, FileMode.Create)) 
            {
                await uploadFile.CopyToAsync(fileStream);
            }

            StatementsDb file = new StatementsDb { StatementsName = uploadFile.FileName, CreateDateTime = DateTime.Now, Path = path}; 

            applicationDb.statementsDbs.Add(file);
            applicationDb.SaveChanges();
        }
        
        return RedirectToAction("Index");
    }
}

Code snippet from the controller with the Remove method

public IActionResult RemoveFile(int statementId)
{
    statementsDb.Remove(statementId);
    return RedirectToAction("Index");
}

Code snippets from the entity in which I'm trying to get the ID

public StatementsDb TryGetByStatementId(int id)
{
    return applicationDb.statementsDbs.FirstOrDefault(statement => statement.StatementsId == id);
}

public void Remove(int statement)
{
    var existingStatement = TryGetByStatementId(statement);
    applicationDb.statementsDbs.Remove(existingStatement);
    applicationDb.SaveChanges();
}

Only afterwards, I get the error System.ArgumentNullException: "Value cannot be null. Arg_ParamName_Name"

Where did I go wrong?

[UPDATE]

using archivingsystem.db;
using archivingsystem.Helpers.AutoMapping;
using AutoMapper;
using Microsoft.EntityFrameworkCore;

namespace archivingsystem
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            IMapper mapper = MappingConfig.RegisterMaps().CreateMapper();

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            builder.Services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


            // AutoMapper
            builder.Services.AddSingleton(mapper);
            builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());


            // Services
            builder.Services.AddTransient<IStatementsDbRepository, StatementsDbRepository>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}


Solution

  • This error is occurring because the existingStatement variable is null. you can add a check for null before calling the Remove method

    if (existingStatement != null)
    {
        applicationDb.statementsDbs.Remove(existingStatement);