TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
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.
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?
Reply
Answers (
1
)
ASP.NET Core Razor Page OnPost with parameter
(Group)Join if you can't use the ICollection