TechieClues TechieClues
Updated date Apr 20, 2023
This article provides a comprehensive guide on how to work with Entity Framework Core in .NET Core, focusing on performing CRUD (Create, Read, Update, Delete) operations on a database.
  • 1.1k
  • 0
  • 0

Introduction:

Entity Framework Core (EF Core) is a popular Object Relational Mapper (ORM) that provides a convenient and efficient way to work with databases in .NET Core applications. With EF Core, developers can map their application domain model to a database schema and perform various CRUD (Create, Read, Update, Delete) operations without writing raw SQL queries.

In this article, we will explore the features and usage of Entity Framework Core in .NET Core. We will cover topics such as setting up EF Core in a .NET Core project, defining models, creating migrations, performing CRUD operations, using relationships, and handling advanced scenarios. We will also provide code examples and explanations to illustrate each concept.

Prerequisites:

Before we dive into EF Core, make sure you have the following prerequisites in place:

  1. Visual Studio or Visual Studio Code installed on your machine.
  2. .NET Core SDK installed (at least version 3.1 or higher).
  3. Basic knowledge of C# and .NET Core.

Setting up EF Core in a .NET Core Project: To start using EF Core in a .NET Core project, follow these steps:

Step 1: Create a new .NET Core project

Open Visual Studio or Visual Studio Code and create a new .NET Core project. You can choose any project template, such as Console App, Web App, or API, based on your application requirements.

Step 2: Install EF Core NuGet package

In the project, install the EF Core NuGet package using the following command in the terminal or package manager console:

dotnet add package Microsoft.EntityFrameworkCore

This will install the EF Core package and its dependencies into your project.

Step 3: Install EF Core Database Provider

EF Core supports multiple database providers, such as SQL Server, MySQL, SQLite, and PostgreSQL. Choose the appropriate database provider based on your database preference and install the corresponding EF Core database provider NuGet package.

For example, to work with SQL Server, install the following package:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Similarly, for MySQL, install the following package:

dotnet add package Microsoft.EntityFrameworkCore.MySQL

You can install other EF Core database providers in a similar way.

Step 4: Define a Database Connection

Next, you need to define a database connection string in your application configuration. This connection string contains information about the database server, authentication details, and the database name.

You can define the connection string in the appsettings.json file in your .NET Core project. Here's an example connection string for SQL Server:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Note: Replace the connection string with your actual database server and database name.

Step 5: Configure EF Core in Startup.cs

In your .NET Core project, open the Startup.cs file and configure EF Core services in the ConfigureServices method. Here's an example configuration for SQL Server:

public void ConfigureServices(IServiceCollection services)
{
  // Add EF Core services
  services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

Note: Replace MyDbContext with the name of your DbContext class and DefaultConnection with the name of your connection string in appsettings.json.

Step 6: Create a DbContext

A DbContext is the main class that represents a database session in EF Core. It provides access to the database and allows you to perform CRUD operations on your entities.

Create a new class that inherits from DbContext and define your entities as DbSet properties.

Here's an example of how you can define a DbContext in EF Core:

using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    // Define your entities as DbSet properties
    public DbSet<User> Users { get; set; }
    public DbSet<Order> Orders { get; set; }
}

In this example, User and Order are the entities that you want to map to the corresponding database tables.

Step 7: Create Models

Next, you need to define your models that represent the entities in your application domain. These models will be used by EF Core to map to the database tables.

Here's an example of how you can define a model for a User entity:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

In this example, User has three properties: Id, Name, and Age. These properties will be mapped to columns in the corresponding database table.

Similarly, you can define models for other entities in your application.

Step 8: Create Migrations

Migrations are used by EF Core to update the database schema based on changes in your models. You need to create migrations whenever you make changes to your models, such as adding, modifying, or deleting properties.

To create a migration, open the terminal or package manager console and run the following command:

dotnet ef migrations add <MigrationName>

Replace <MigrationName> with a meaningful name for your migration. EF Core will generate a migration file in your project's Migrations folder with the necessary code to update the database schema.

For example:

dotnet ef migrations add InitialCreate

This command creates an initial migration for your models.

Step 9: Apply Migrations

After creating a migration, you need to apply it to the database to update the schema. Run the following command in the terminal or package manager console:

dotnet ef database update

This command applies the pending migrations to the database and creates the corresponding tables.

CRUD Operations with EF Core:

Now that you have set up EF Core in your .NET Core project, defined models, and created migrations, you can start performing CRUD operations on your entities using the DbContext.

Let's go through some common CRUD operations using EF Core:

1. Create (Insert) Operation:

To add a new entity to the database, you can create a new instance of the entity model, set its properties, and add it to the DbSet of the DbContext. Finally, call SaveChanges on the DbContext to persist the changes to the database.

Here's an example of how you can insert a new User entity into the database:

using (var dbContext = new MyDbContext())
{
    var newUser = new User
    {
        Name = "John",
        Age = 30
    };

    dbContext.Users.Add(newUser);
    dbContext.SaveChanges();
}

In this example, a new User entity with the name "John" and age 30 is created and added to the Users DbSet of the MyDbContext. Then, SaveChanges is called to persist the changes to the database.

2. Read (Select) Operation:

To retrieve entities from the database, you can use the DbSet properties of the DbContext to query the database.

Here's an example of how you can retrieve all User entities from the database:

using(var dbContext = new MyDbContext()) {
  var users = dbContext.Users.ToList();
  foreach(var user in users) {
    Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Age: {user.Age}");
  }
}

In this example, `Users` property of `MyDbContext` is used to query the database and retrieve all `User` entities. The retrieved entities are then printed to the console.

3. Update Operation:

To update an existing entity in the database, you can first retrieve the entity from the DbContext, modify its properties, and then call `SaveChanges` to persist the changes to the database.

Here's an example of how you can update the age of a `User` entity in the database:

using (var dbContext = new MyDbContext())
{
    var user = dbContext.Users.FirstOrDefault(u => u.Name == "John");
    if (user != null)
    {
        user.Age = 31;
        dbContext.SaveChanges();
    }
}

In this example, FirstOrDefault method is used to retrieve a User entity with the name "John" from the database. If the entity is found, its age is updated to 31 and SaveChanges is called to persist the changes to the database.

4. Delete Operation:

To delete an entity from the database, you can first retrieve the entity from the DbContext, remove it from the DbSet, and then call SaveChanges to persist the changes to the database.

Here's an example of how you can delete a User entity from the database:

using (var dbContext = new MyDbContext())
{
    var user = dbContext.Users.FirstOrDefault(u => u.Name == "John");
    if (user != null)
    {
        dbContext.Users.Remove(user);
        dbContext.SaveChanges();
    }
}

In this example, FirstOrDefault method is used to retrieve a User entity with the name "John" from the database. If the entity is found, it is removed from the Users DbSet of the MyDbContext and SaveChanges is called to persist the changes to the database.

Conclusion:

In this article, we discussed how to work with Entity Framework Core in .NET Core to perform CRUD operations on a database. We covered the steps to set up EF Core in a .NET Core project, define models, create migrations, and apply them to the database. We also went through examples of how to perform create, read, update, and delete operations using EF Core's DbContext. EF Core provides a powerful and flexible way to work with databases in .NET Core applications, making it easier to manage database operations and interact with data in your application.

Reference Article: Build ASP.NET Core Web API with CRUD Operations Using Entity Framework Core

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!