如何使用TryUpdateModel [英] How to use TryUpdateModel

查看:258
本文介绍了如何使用TryUpdateModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在准备本教程。我从本教程看到,为了更新,作者正在使用以下代码:

I am readying this tutorial. I see from this tutorial that for update the author is using the following code:

....
var studentToUpdate = db.Students.Find(id);
if (TryUpdateModel(studentToUpdate, "",
   new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
{
    try
    {
        db.Entry(studentToUpdate).State = EntityState.Modified;
        db.SaveChanges();

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

了解为什么需要以下行:

But I don't understand why the following line is needed:

db.Entry(studentToUpdate).State = EntityState.Modified;

当我删除此行时,代码仍然运行正常,更新完成。
有人可以帮助我天气吗?

When I remove this line, the code still works well and update is done perfectly. Can someone help me weather that line is needed? If so, why when I remove it, the update works well.

推荐答案

它工作得很好,因为你发现 studentToUpdate 从您的上下文中,这是实体的附加方式,并且当您调用 TryUpdateModel 方法所做的更改时, code> SaveChanges 方法。

It works well because you find the studentToUpdate from your context, that's way the entity is attached and the changes that are made by the TryUpdateModel method are saved when you call the SaveChanges method.

如果您正在使用独立的实体,例如:

If you were working with a detached entity, for example doing this:

var studentToUpdate=new Student(){Id=id};
if (TryUpdateModel(studentToUpdate, "",
   new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
{
    try
    {
        db.Entry(studentToUpdate).State = EntityState.Modified;
        db.SaveChanges();

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

在这种情况下必须调用 Entry 方法将实体附加到您的上下文并更改其状态。

In this case you have to call the Entry method to attach the entity to your context and change its state.

这篇关于如何使用TryUpdateModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆