Reputation: 1220
As the title suggests how can I get information back after saving changes with Entity Framework to sql in MVC.
I have a create method and I wanted to find out, if when a user saves a post how could I get the ID of the saved post back in the same view?
// GET: /Post/Create
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create(Post post)
{
try
{
if (ModelState.IsValid)
{
db.Posts.Add(post);
db.SaveChanges();
}
}
Upvotes: 0
Views: 2211
Reputation: 2982
After you've saved an entity in the context SaveChanges()
. The ID
property on the poco itself should be set by the entity framework.
Look at post.Id
after saving and it will be there!
If you are POSTing something other than the Post object with the form, you need to change the action method signature to have some kind of object for it to bind to, then save changes:
public ActionResult Create(Post post, OtherPartialViewItem item)
then
db.OtherPartialViewItem.Add(item); db.SaveChanges();
Upvotes: 2