In Framework, updating records is one of the most common and frequent CRUD operations when we build an application.
Updating records involves modifying the values of an entity that already exists in the database. For this, Entity Framework tracks changes in the entities being managed by the context (DbContext
).
When you call the SaveChanges()
method, Entity Framework generates and executes the necessary SQL statements to reflect the changes in the database.
There are several main approaches to updating entities:
- Update an object from the DbContext
- Use the
Update()
method
Updating an Entity from the DbContext
The most common way is simply to update one of the entities in the DbContext
. For example,
using (var context = new SchoolContext())
{
var student = context.Students.Find(1); // Search by primary key
if (student != null)
{
student.Name = "New Name"; // Update the name
student.Age = 21; // Update the age
context.SaveChanges(); // Save changes to the database
}
}
In this example:
Find(1)
searches for the student with a primary key equal to 1.- The properties
Name
andAge
of thestudent
object are updated. SaveChanges()
saves the changes made to the database.
Updating Records with Update
The Update
method is a straightforward way to mark an entity as modified.
When this method is called, Entity Framework assumes that the entity has been altered and that it should generate an SQL UPDATE
statement to synchronize the changes in the database.
dbContext.Update(entity);
dbContext.SaveChanges();
Suppose we have a Product
entity with the following properties:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
To update an existing product, we first retrieve it from the database, modify its properties, and then call the Update
method:
using (var dbContext = new MyDbContext())
{
// Retrieve the product to update
var product = dbContext.Products.Find(1); // Suppose the Id is 1
if (product != null)
{
// Modify the properties
product.Name = "New Name";
product.Price = 99.99m;
// Mark the entity as modified
dbContext.Update(product);
// Save changes to the database
dbContext.SaveChanges();
}
}
In this example, Entity Framework will generate an SQL UPDATE
statement to update the product with Id = 1
.
Update
marks all properties of the entity as modified, which can generate an SQL UPDATE
statement that includes all columns, even if only one was modified.