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();
}
}
}
CodePudding user response:
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);
CodePudding user response:
I think it might be a problem with your url, you may not get the statement
, that is to say, the statement
is always 0, so you cannot get the data. What is your url for the Remove request?
From your current code, your url should look like this:
https://localhost:xxx/Management/Remove?statement=1
At this point you can see that the statement
is 1, and the id
of TryGetByStatementId
is also 1:
If you want to use a url like this:
https://localhost:xxx/Management/Remove/2
Then you need to add attribute route for Remove
:
[Route("[controller]/[action]/{statement:int}")]
At this point you can see that the statement
is 2, and the id
of TryGetByStatementId
is also 2:
If you can get the id
correctly, then you should be able to get the corresponding data from the database.