Entity Framework Core (EF Core) provides a straightforward way to perform basic CRUD (Create, Read, Update, Delete) operations on a database using a DbContext. Here’s how you can set up and perform each operation.
Setup
Install EF Core: Ensure you have the EF Core package installed via NuGet:
Create Model Classes: Define your model classes, for example,
Product:Set up DbContext: Create a
DbContextclass to manage the entity models.
CRUD Operations
1. Create Operation
To add new data, create an instance of the model, add it to the context, and call SaveChanges to persist it to the database.
This will insert a new row into the Products table.
2. Read Operation
To read or retrieve data, use LINQ queries on the DbSet. You can retrieve single items or lists.
Find works with the primary key and is optimized for quick lookups, while Where allows for more complex querying.
3. Update Operation
To update data, retrieve the entity, modify its properties, and call SaveChanges. EF Core tracks changes automatically.
When you call SaveChanges, EF Core will generate an SQL UPDATE command for the modified entity.
4. Delete Operation
To delete data, retrieve the entity you want to remove, call Remove, and then SaveChanges.
This will generate a DELETE SQL command to remove the specified row from the Products table.
Additional Tips
Asynchronous Methods: EF Core also provides asynchronous versions for all CRUD operations, such as
AddAsync,FindAsync,ToListAsync, andSaveChangesAsync. These are useful for non-blocking operations in a web environment.Tracking: By default, EF Core tracks changes to entities. You can disable tracking on read operations for performance using
AsNoTracking, which is useful when you’re only reading data and don’t intend to update it.
Summary Table
| Operation | Method | Description |
|---|---|---|
| Create | Add / AddAsync | Adds a new entity to the database. |
| Read | Find / Where / ToList | Retrieves data from the database. |
| Update | Modify properties + SaveChanges | Updates the entity and saves changes to the database. |
| Delete | Remove + SaveChanges | Deletes an entity from the database. |
With these CRUD operations, you can manage basic data interactions in an EF Core-powered .NET Core application.
0 comments:
Post a Comment