1

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 with whether that line is needed? If so, why when I remove it, the update works well.

InspiredBy
  • 4,271
  • 6
  • 40
  • 67
user3389168
  • 59
  • 1
  • 4

2 Answers2

1

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");
    }
...
}

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

ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • Thanks, but what's your advice? Is it better to keep that line or remove it for this specific example? I personally prefer to remove it because it's confusing (at least for me). But maybe I am missing something? – user3389168 Mar 06 '15 at 18:02
  • well, if you find the entity from you context, you don't need to call the `Entry` method to change the state of the entity, unless you've disabled the change tracking – ocuenca Mar 06 '15 at 18:03
0

That line is explicitly telling the EF context that the entity has been modified and needs to be updated the next time SaveChanges() is called. The reason everything still works when you remove that line is that the context usually tracks those changes automatically for you. I have yet to come across a situation where I have needed to fiddle with EF's automatic change tracking in production, it seems to work well.

See How change tracking works in Entity Framework for a bit more info.

Community
  • 1
  • 1
Paul Griffin
  • 2,416
  • 15
  • 19