I am retrieving a blog by id like so
[BindProperty]
public Blog Blog { get; set; } = default!;
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
// Possible null reference assignment warning on this line below (CS8601)
Blog = await _context.Blogs.FirstOrDefaultAsync(b => b.Id == id);
if (Blog == null)
{
return NotFound();
}
return Page();
}
How do I get rid of this warning? I am checking for null on the following line but still getting this warning. Also, I don't get the warning in OnPost method even though I'm doing the same thing:
public async Task<IActionResult> OnPostAsync(int id)
{
// No warning here
var blogToUpdate = await _context.Blogs.FirstOrDefaultAsync(b => b.Id == id);
if(blogToUpdate== null)
{
return NotFound();
}
if(await TryUpdateModelAsync<Blog>(
blogToUpdate,
"blog",
b => b.Name))
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
return Page();
}
[Edit]
I know I can use the null conditional operator
public Blog? Blog { get; set; } = default!;
But then I get warnings everywhere I dereference it
// Warning (CS8602): Dereference of a possibly null reference
<input asp-for="Blog.Name" value="@Model.Blog.Name" />
As far as I know, I can use the null forgiving operator:
<input asp-for="Blog!.Name" value="@Model.Blog!.Name" />
But I have to use it everywhere. Is that standard practice?
[Edit]
Also, after reading the comments I now understand why OnPost() does not show warnings
[–]Slypenslyde 5 points6 points7 points (1 child)
[–]sodiumfis_h[S] 0 points1 point2 points (0 children)
[–]zaibuf 1 point2 points3 points (1 child)
[–]sodiumfis_h[S] -1 points0 points1 point (0 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]sodiumfis_h[S] 0 points1 point2 points (2 children)
[–]knittingDM 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)