Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Now we're ready to update the comic books controller to handle creates and updates. Let's finish the "Add Comic Book" page before we move on to the "Update Comic Book" page.
Follow Along
To follow along committing your changes to this course, you'll need to fork the dotnet-comic-book-library-manager repo. Then you can clone, commit, and push your changes to your fork like this:
git clone <your-fork>
cd dotnet-comic-book-library-manager
git checkout tags/v2.5 -b handling-creates-and-updates
Keyboard Shortcuts
-
CTRL+K
CTRL+U
- Uncomment Selection
Avoiding Updating Every Table Column
Let's look at a couple of approaches that you can use to avoid EF creating a SQL update statement that updates every table column.
First off, if you're just looking to prevent updating a single column (or handful of columns), you can use an entity's context entry to change a property's IsModified
property to false
. For example, this line of code would keep the IssueNumber
column from being included in the SQL update statement:
comicBookEntry.Property("IssueNumber").IsModified = false;
Another approach is to retrieve the entity from the database (so that the context is tracking it) and then update that entity with the new values from the user's post data. A convenient way of doing that is to use the Controller class' UpdateModel
or TryUpdateModel
method to update the entity that's retrieved from the database.
// Creating an anonymous object here in order to keep the shape of the model
// the same as the incoming form post data.
var comicBookToUpdate = new
{
ComicBook = _comicBooksRepository.Get(comicBook.Id)
};
UpdateModel(comicBookToUpdate);
Context.SaveChanges();
The downside of this approach is that it requires an additional query to load the entity into the context and an additional model binding pass.
Security Considerations
When relying upon modeling binding to populate view model or entity values, an important security consideration for ASP.NET MVC developers to consider is an issue known as "over posting". Over posting is when users manipulate a request to include additional form post name/value pairs (beyond those that are included in the form itself).
We'll look at how to resolve this issue in a future security related course. For more information on this issue and ways to prevent it, see this excellent blog post from K. Scott Allen:
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up