Examples

C# Database CRUD

Building a CRUD App

C# database CRUD with EF Core handles data operations.

Introduction to EF Core

Entity Framework Core (EF Core) is a modern object-database mapper for .NET. It enables developers to work with a database using .NET objects, eliminating the need for most data-access code. EF Core supports many database engines, including SQL Server, PostgreSQL, MySQL, and SQLite.

Setting Up the Project

To start working with EF Core for CRUD operations, you need to set up a .NET Core console application. Ensure you have the latest .NET SDK installed. You can create a new project using the following command:

Navigate to the project directory and add the necessary EF Core packages:

Defining the Model

Let's define a simple model class representing an entity. In this example, we'll use a Product class:

Creating the Database Context

The database context is the main class that coordinates Entity Framework functionality for a given data model. Create a class AppDbContext that inherits from DbContext:

Performing CRUD Operations

Now that we have our model and DbContext set up, we can perform CRUD operations. Below are examples for each operation:

Create Operation

To add a new product to the database, use the following code:

Read Operation

To read products from the database, you can query the Products DbSet:

Update Operation

To update an existing product, find it and modify its properties:

Delete Operation

To delete a product, find it and remove it from the DbSet:

Conclusion

EF Core streamlines database operations in C# applications by abstracting the underlying database interactions. By using EF Core, you can perform CRUD operations with minimal code, allowing you to focus more on the business logic of your application.