Step-by-Step Guide to Entity Framework in .NET

Lucas Andrade
4 min readOct 20, 2023

--

Introduction

Entity Framework (EF) is a powerful and widely used Object-Relational Mapping (ORM) tool for .NET Core developers. It simplifies database interactions by allowing you to work with database objects as if they were regular C# objects.

In this step-by-step guide, we’ll walk you through the process of installing and implementing Entity Framework in a .NET Core application. We’ll also use SQL Server as the database and show you how to install the required NuGet package, EntityFrameworkCore.SqlServer.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  1. .NET Core SDK: Download and install the .NET Core SDK from the official website (https://dotnet.microsoft.com/download).
  2. Visual Studio or Visual Studio Code: You can use your preferred Integrated Development Environment (IDE).
  3. SQL Server: Install and set up SQL Server on your machine or use an existing SQL Server instance.

Step 1: Create a New .NET Core Project

Open your command-line interface or IDE, and create a new .NET Core project by running the following command:

dotnet new console -n EFCoreExample

This command will create a new console application with the name “EFCoreExample.”

Step 2: Install Entity Framework Core

To use Entity Framework in your project, you need to install the EntityFrameworkCore.SqlServer package. Navigate to your project folder and run the following command:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Or use the Nuget Package manager:

Step 3: Create a Class

In this example, we’ll create a User class to represent the data we want to store in the database. Create a new file named “User.cs” in your project and define the User class as follows:

using System;

namespace EFCoreExample
{
public class User
{
public int Id { get; private set; }
public string Name { get; private set; }
public string Email { get; private set; }
public List<Role> Roles { get; private set; }
}
}

Step 4: Create the DbContext

Entity Framework uses a DbContext class to represent your database and its tables. Create a new file named “AppDbContext.cs” in your project and define your DbContext class:

using Microsoft.EntityFrameworkCore;

namespace EFCoreExample
{
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
}

The DbSet<> is used to represent the tables that your entities represent.

While the OnModelCreating() method maps the entities by the assembly, and each entity should have a map class, like:

public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(u => u.Id);

builder.HasMany(u => u.Roles)
.WithOne()
.HasForeignKey(r => r.Id)
.OnDelete(DeleteBehavior.Restrict);
}
}

Step 5: Configure the Database connection

For the DbContext function how it musts, the database must be configured, and we do that by configuring the ConnectionString. For that, on your appsettings.json you must add:

"ConnectionStrings": {
"MyAppCs": "Server=localhost\\SQLEXPRESS; Database=MyApp; Integrated Security=True; trustServerCertificate=true"
},

Then, on the Program.cs add the following:

var connectionString = builder.Configuration.GetConnectionString("MyAppCs");
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));

Step 6: Create a migration

Now that you’ve set up your User class and DbContext, it’s time to create and apply the database migration. In your project directory, run the following commands:

dotnet ef migrations add InitialMigration
dotnet ef database update

Or use the Package Manager Console:

Add-Migration InitialMigration
Update-Database

These commands will create the initial database migration and apply it to your SQL Server instance. At this step, your appsettings.json must have your ConnectionString already.

Step 7: Implement Entity Framework in Your Application

Now, you can use Entity Framework to interact with the database in your application. Here’s an example of how to add a new user to the database:

public class UserService
{
public readonly AppDbContext_dbContext;

public UserService(AppDbContext dbContext)
{
_dbContext = dbContext;
}

public async Task AddUser(User user)
{
await _dbContext.Users.AddAsync(user);
await _dbContext.SaveChangesAsync();
}

public async Task<User> GetAllUser(string name)
{
return await _dbContext.Users
.Include(user => user.Roles)
.FirstOrDefaultAsync(user => user.FullName == name);
}
}

Conclusion

You have successfully installed and implemented Entity Framework in a .NET Core application.

Entity Framework simplifies database operations and allows you to work with your data using C# objects. You can now build upon this foundation to create more complex database-driven applications with ease.

--

--