Let's take a look at how we can change the data after inserting it. This is done in the SQL world by issuing an UPDATE
command. In the Entity Framework world, you do not need to perform this step. Instead, we just need to find an instance of an object in the collection, change its properties, and then call the familiar SaveChanges
method. Now, we just need to get an object from the database to update. You just saw how to do this in the Querying data in a database section. Here is what the update code looks like:
using (var context = new Context()) { var savedPeople = context.People; if (savedPeople.Any()) { var person = savedPeople.First(); person.FirstName = "Johnny"; person.LastName = "Benson"; context.SaveChanges(); } }
As you can see, we simply point to the People
property of the context. Then, we check to make sure that there is at least one entity in the collection using the Any()
method, which is part of LINQ. Then, we...