Saving Data with Entity Framework
Saving data is a fundamental operation when working with any data access technology. Entity Framework (EF) simplifies this process by allowing you to work with your data as objects and then persist those changes back to the database with minimal code.
Understanding the DbContext
The DbContext
is the primary class that represents a session with the database and allows you to query and save data. It tracks changes to entities and manages the persistence of those changes.
DbContext
when you are finished with it, typically by using a using
statement. This releases database connections and other resources.
Adding New Entities
To add a new record to your database, you create an instance of your entity class, populate its properties, and then add it to the appropriate DbSet<TEntity>
in your DbContext
.
// Assuming 'context' is an instance of your DbContext
var newProduct = new Product { Name = "New Gadget", Price = 99.99m };
context.Products.Add(newProduct);
context.SaveChanges();
Modifying Existing Entities
Entity Framework automatically tracks changes to entities that are loaded into the DbContext
. When you retrieve an entity, modify its properties, and then call SaveChanges()
, EF will generate the appropriate SQL UPDATE statements.
// Assuming 'context' is an instance of your DbContext and 'productToUpdate' is retrieved from the database
var productToUpdate = context.Products.Find(1); // Find product with ID 1
if (productToUpdate != null)
{
productToUpdate.Price = 129.50m;
productToUpdate.Name = "Updated Gadget";
context.SaveChanges();
}
Deleting Entities
To delete an entity, you first retrieve it from the DbContext
and then call the Remove()
method on the corresponding DbSet<TEntity>
.
// Assuming 'context' is an instance of your DbContext and 'productToDelete' is retrieved from the database
var productToDelete = context.Products.Find(2); // Find product with ID 2
if (productToDelete != null)
{
context.Products.Remove(productToDelete);
context.SaveChanges();
}
Saving Multiple Changes
You can add, modify, and delete multiple entities within a single DbContext
instance and then call SaveChanges()
once to persist all these changes to the database efficiently.
Example: Batch Save Operations
using (var context = new MyDbContext())
{
// Add a new order
var newOrder = new Order { OrderDate = DateTime.Now };
context.Orders.Add(newOrder);
// Update a product's price
var productToUpdate = context.Products.Find(5);
if (productToUpdate != null)
{
productToUpdate.Price = 55.00m;
}
// Delete an old product
var productToDelete = context.Products.Find(10);
if (productToDelete != null)
{
context.Products.Remove(productToDelete);
}
// Save all changes atomically
context.SaveChanges();
}
Handling Concurrency Conflicts
Concurrency control is important to prevent data loss when multiple users might be modifying the same data simultaneously. Entity Framework provides mechanisms to handle these conflicts. Refer to the "Transactions and Concurrency" section for more details.
SaveChanges()
, EF executes the necessary SQL commands against the database. If an error occurs during this process, an exception will be thrown.