One Difference Entity State in Desktop App vs in Web App


Microsoft’s Entity Framework now released at least 4 or even 5 main versions, there are many new stuff should to learn for most of Microsoft tech programmers who want to turn to MVC and Entity Framework.

Here I record one small point: One difference about Entity State in desktop application and in web application:

Normally an Entity State has the 5 states:  Added, Unchanged, Modified, Deleted, Detached.

When you edit an item in a MVC web application, normally you have the code like the following:

        public ActionResult Edit(Student student)
            if (ModelState.IsValid)
                db.Entry(student).State = EntityState.Modified;
                return RedirectToAction("Index");

            return View(student);

You can see before save the edition, we set the Entity State to Modified, this step is necessary for a MVC web application, otherwise you can not save your edition.

However, in a local desktop application, the Entity State is set automatically.

Please read the following content which is from Microsoft’s tutorial: Getting Started with EF using MVC

In a desktop application, state changes are typically set automatically. In this type of application, you read an entity and make changes to some of its property values. This causes its entity state to automatically be changed toModified. Then when you call SaveChanges, the Entity Framework generates a SQL UPDATE statement that updates only the actual properties that you changed.

However, in a web application this sequence is interrupted, because the database context instance that reads an entity is disposed after a page is rendered. When the HttpPost Edit action method is called, this is the result of a new request and you have a new instance of the context, so you have to manually set the entity state to Modified.Then when you call SaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.