[英]System.ArgumentNullException: 'Value cannot be null. Arg_ParamName_Name'
[英]ASP.NET .NET6 System.ArgumentNullException: "Value cannot be null. Arg_ParamName_Name"
我有一個 TryGetByStatementId 方法,它使用FirstOrDefault
方法從數據庫中返回 id。
我還有一個數據庫,用於存儲有關上傳文件的信息。 我通過controller上傳文件,文件保存在wwwroot的文件系統中,數據庫中保存了id、Name、CreateDateTime等信息。 當我嘗試使用 TryGetByStatementId 方法刪除信息時,出現錯誤 -> System.ArgumentNullException: "Value cannot be null.Arg_ParamName_Name"
我下載文件並將其保存到文件系統的 controller
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");
}
}
來自 controller 的帶有 Remove 方法的代碼片段
public IActionResult RemoveFile(int statementId)
{
statementsDb.Remove(statementId);
return RedirectToAction("Index");
}
我試圖在其中獲取 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();
}
直到后來,我才收到錯誤 System.ArgumentNullException: "Value cannot be null.Arg_ParamName_Name"
我go哪里錯了?
[更新]
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();
}
}
}
發生此錯誤是因為 existingStatement 變量為null
。 您可以在調用Remove
方法之前添加對null
的檢查
if (existingStatement != null)
{
applicationDb.statementsDbs.Remove(existingStatement);
我覺得可能是你的url有問題,你可能拿不到statement
,也就是說statement
一直是0,所以拿不到數據。 刪除請求的 url 是多少?
根據您當前的代碼,您的 url 應如下所示:
https://localhost:xxx/Management/Remove?statement=1
此時可以看到statement
為1, TryGetByStatementId
的id
也為1:
如果你想這樣使用 url:
https://localhost:xxx/Management/Remove/2
然后你需要為Remove
添加屬性路由:
[Route("[controller]/[action]/{statement:int}")]
此時可以看到statement
是2, TryGetByStatementId
的id
也是2:
如果能正確獲取到id
,那么應該就可以從數據庫中獲取到相應的數據了。
我這樣解決了問題:
public IActionResult RemoveFile(Guid statementId)
{
var removeF = statementsDb.TryGetByStatementId(statementId);
statementsDb.Remove(removeF.StatementsId);
return RedirectToAction(nameof(Index));
}
和
public void Remove(Guid statement)
{
var fileId = applicationDb.statementsDbs.FirstOrDefault(x => x.StatementsId == statement);
applicationDb.statementsDbs.Remove(fileId);
applicationDb.SaveChanges();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.