Cop Blaster

Cop Blaster

  • NA
  • 39
  • 347

Why Can't I Get the Scoped Identity From EF After a Record is Saved?

Oct 26 2020 10:51 PM
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.
  1. public async Task < IActionResult > OnPostAsync() {  
  2.   if (!ModelState.IsValid) {  
  3.     return Page();  
  4.   }  
  5.   _context.Posts.Add(Posts);  
  6.   await _context.SaveChangesAsync();  
  7.   int postid = Posts.Postid;  
  8.   string targeturl = linkgenerator.postlink(Posts.Postid, Posts.Title);  
  9.   return RedirectToPage(targeturl);  
  10. }  
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?

Answers (1)