简体   繁体   English

在使用Entity Framework和MVC保存更改后如何获取信息

[英]how to get information back after saving changes with Entity Framework and MVC

As the title suggests how can I get information back after saving changes with Entity Framework to sql in MVC. 正如标题所示,在MVC中使用Entity Framework将更改保存到sql之后,如何获取信息。

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? 我有一个create方法,我想找出一个问题,当用户保存帖子时,如何在同一视图中找回已保存帖子的ID?

    // 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();
            }
        }

After you've saved an entity in the context SaveChanges() . 在上下文中保存实体后, SaveChanges() The ID property on the poco itself should be set by the entity framework. poco本身的ID属性应由实体框架设置。

Look at post.Id after saving and it will be there! post.Id后查看post.Id ,它将在那里!

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: 如果您要使用表单发布除Post对象之外的其他内容,则需要更改操作方法签名以使其具有绑定到的某种对象,然后保存更改:

public ActionResult Create(Post post, OtherPartialViewItem item)

then 然后

db.OtherPartialViewItem.Add(item); db.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM