I have this code that successfully creates a new entry in my Posts table but for some reason the Postid is null even though I don't try to access it until after the new record is created.
- public async Task < IActionResult > OnPostAsync() {
- if (!ModelState.IsValid) {
- return Page();
- }
- _context.Posts.Add(Posts);
- await _context.SaveChangesAsync();
- int postid = Posts.Postid;
- string targeturl = linkgenerator.postlink(Posts.Postid, Posts.Title);
- return RedirectToPage(targeturl);
- }
According to this tutorial all I need to do to access a newly created primary key is to type the name of the table followed by a "." and the name of the column https://www.entityframeworktutorial.net/faq/how-to-get-id-of-saved-entity-in-entity-framework.aspx but the above code returns a null value instead of the newly created Postid.
Most of the new record is created using a form on a Razor Page. The above code is from code behind on that page. After checking the database I can confirm that the new record is in fact created. Please word any response in a way that someone familiar with WebForms and not familiar at all with MVC can understand. I chose to convert my WebForms site to a .Net Core Razor Pages site because I was given the impression that it is closer to WebForms than any other modern option that uses the .Net Framework. So far it seems nothing like WebForms. Am I at least correct in believing that the OnPostAsync event in a Razor Page is the equivalent of the FormView_ItemInserting event in a WebForm?
UPDATE: Looking back it appears that I was never able to use the new primary key value in my WebForm until the SqlDataSource1_Inserted event. Is it possible to get the primary key during the same event on a Razor Page or do I need to add a second task that runs after the first one?