The Basics of Saving Data
Entity Framework Core (EF Core) provides a powerful and flexible way to interact with your database. One of the fundamental operations is saving data—inserting new records, updating existing ones, and deleting unwanted entries.
EF Core tracks changes made to entities that are attached to a DbContext
. When you call the SaveChanges()
or SaveChangesAsync()
method on your context, EF Core determines what operations need to be performed on the database based on the state of these tracked entities.
Adding New Entities
To add a new entity, you first create an instance of your entity class and then add it to a DbSet<TEntity>
exposed by your DbContext
. EF Core will then generate an `INSERT` statement when SaveChanges()
is called.
// Assuming 'context' is an instance of your DbContext
var newUser = new User { Name = "Alice", Email = "alice@example.com" };
context.Users.Add(newUser);
await context.SaveChangesAsync(); // Inserts the new user into the database
Modifying Existing Entities
EF Core automatically tracks changes to entities that are retrieved from the database. If you fetch an entity, modify its properties, and then call SaveChanges()
, EF Core will generate an `UPDATE` statement for that entity.
// Assuming 'context' and 'userToUpdate' are already set up
var userToUpdate = await context.Users.FindAsync(1); // Get user with ID 1
if (userToUpdate != null)
{
userToUpdate.Name = "Alice Smith"; // Modify a property
await context.SaveChangesAsync(); // Updates the user in the database
}
Deleting Entities
To delete an entity, you typically retrieve it from the database and then use the Remove()
method on the DbSet<TEntity>
. EF Core will then generate a `DELETE` statement.
// Assuming 'context' and 'userToDelete' are already set up
var userToDelete = await context.Users.FindAsync(2); // Get user with ID 2
if (userToDelete != null)
{
context.Users.Remove(userToDelete);
await context.SaveChangesAsync(); // Deletes the user from the database
}
Understanding Entity States
EF Core tracks the state of each entity it manages. Common states include:
- Added: The entity is new and will be inserted.
- Modified: The entity's properties have been changed.
- Deleted: The entity will be removed.
- Unchanged: The entity has not been changed since it was loaded or last saved.
- Detached: The entity is not being tracked by the context.
You can explicitly change the state of an entity using the Entry()
method and the State
property, although for most common scenarios, EF Core handles state tracking automatically.
Multiple Operations in One Save
A single call to SaveChanges()
can perform multiple operations (adds, updates, deletes) across different entities and DbSet
s. EF Core efficiently batches these operations for optimal database performance.
// Add a new user
var newUser = new User { Name = "Bob", Email = "bob@example.com" };
context.Users.Add(newUser);
// Update an existing user
var userToUpdate = await context.Users.FindAsync(1);
if (userToUpdate != null)
{
userToUpdate.Name = "Alice Wonderland";
}
// Delete another user
var userToDelete = await context.Users.FindAsync(3);
if (userToDelete != null)
{
context.Users.Remove(userToDelete);
}
await context.SaveChangesAsync(); // All changes are applied atomically
Next Steps
In the next section, we'll delve into managing relationships between entities, a crucial aspect of database design.