简体   繁体   English

使用MVC4 +实体框架更新模型4

[英]Updating Model using MVC4 + Entity Framework 4

I am trying to learn MVC & EF to move away from WebForms and ADO.NET. 我正在努力学习MVC和EF,以摆脱WebForms和ADO.NET。 I am just throwing together my first trial site so see how it goes and have hit a stumbling block. 我只是把我的第一个试验网站扔到一起,所以看看它是怎么回事并且遇到了绊脚石。

I am editing a record on the page and pressing save.I get no errors returned however the data is not updated. 我正在页面上编辑记录并按save.I没有返回错误,但数据没有更新。

The Article Model being updated 文章模型正在更新

    public class Article
{
    [Key]
    public int Id { get; set; }

    public string Author { get; set; }
    public string Title { get; set; }
    public DateTime DateCreated { get; set; }
    public string Body { get; set; }
    public int Likes { get; set; }
    public int Dislikes { get; set; }
    public List<Comment> Comments { get; set; }
    public string Tags { get; set; }
    public int Category { get; set; }
}

The edit code on the Controller, the articleId is from the querystring. Controller上的编辑代码,articleId来自查询字符串。

    [HttpPost]
    public ActionResult Edit(int articleId, FormCollection collection)
    {
        var result = from i in db.Articles
                     where i.Id == articleId
                     select i;

        if (TryUpdateModel(result))
        {
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(result.First());

    }

On debugging, the TryUpdateModel() returns true and calls the db.SaveChanges. 在调试时,TryUpdateModel()返回true并调用db.SaveChanges。 No errors are returned. 没有错误返回。 When being directed back to the Index method on the Controller, the article is showing unchanged. 当被引导回Controller上的Index方法时,文章显示未更改。

Is it something glaringly obvious? 这是明显的东西吗?

Many Thanks 非常感谢

I had forgotton to select the model out of the enumerable. 我已经忘了从可枚举中选择模型了。 Adding .First() to select the record fixed it. 添加.First()以选择修复它的记录。 Just one of those occasions where I couldn't see the wood from the trees! 只是其中一个我无法从树上看到木头的场合!

    [HttpPost]
    public ActionResult Edit(int articleId, FormCollection collection)
    {
        var result = from i in db.Articles
                     where i.Id == articleId
                     select i;

        if (TryUpdateModel(result.First()))
        {

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(result.First());

    }

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

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