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 get the first object in the collection using the First()
method. We could have just as easily pointed to any other object in the collection. After this, we set two properties of the found Person
object to some new values. Finally, we issue SaveChange()
just like in the example of the insert operation. If you run this code while SQL Server Profiler is running, you will see the SQL queries that Entity Framework creates and issues in conjunction with the SQL Server Entity Framework provider. Entity Framework maintains the state of changed objects and is responsible for generating appropriate update queries. Here is how the same code looks in VB.NET:
Using context = New Context() Dim savedPeople = context.People If savedPeople.Any() Then With savedPeople.First() .FirstName = "Johnny" .LastName = "Benson" End With context.SaveChanges() End If End Using
18.188.198.94