aspnet-core-integrar-entity-framework-configuracion

Entity Framework Core in ASP.NET Core: Configuration

  • 4 min

Entity Framework Core is the .NET ORM for working with databases using C# classes.

We’ve reached the point of persisting data. So far, our API was “amnesic”: if you restarted the server, you lost the in-memory data.

To save information, we’ll use .NET’s premier ORM: Entity Framework Core (EF Core).

Today we will learn how to configure the engine so that your API can communicate with the database.

Package Installation

EF Core is modular. We don’t install a monolith, but the pieces we need. For a typical API with SQL Server, we need to install these NuGet packages:

The Core:

Microsoft.EntityFrameworkCore

The Provider (Driver):

Microsoft.EntityFrameworkCore.SqlServer (for PostgreSQL we would use Npgsql.EntityFrameworkCore.PostgreSQL; for SQLite, Microsoft.EntityFrameworkCore.Sqlite).

The Tools (Commands):

Microsoft.EntityFrameworkCore.Tools (for the Visual Studio Package Manager Console) or Microsoft.EntityFrameworkCore.Design (for the CLI).

In your terminal:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design dotnet tool install —global dotnet-ef

The DbContext

The heart of EF Core is the DbContext. It is the class that represents a session with the database.

To integrate it into ASP.NET, we must create a class that inherits from DbContext and, very importantly, has a constructor that accepts configuration options.

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    // Mandatory constructor for Dependency Injection to work
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    // Your tables (DbSets)
    public DbSet<Producto> Productos { get; set; } = null!;
    public DbSet<Usuario> Usuarios { get; set; } = null!;
}
Copied!

The Connection String

As we saw in the configuration block, we never write passwords or IP addresses in C# code. The connection string goes into the configuration file.

Open appsettings.json and add the ConnectionStrings section:

{ “ConnectionStrings”: { “DefaultConnection”: “Server=localhost;Database=MiApiDb;Trusted_Connection=True;TrustServerCertificate=True;” } }

If you use SQL Server LocalDB (the one that comes with Visual Studio), the string is usually: Server=(localdb)\\mssqllocaldb;Database=MiApiDb;Trusted_Connection=True;

Configuration in Program.cs

Now we need to register our ApplicationDbContext in the Dependency Injection container so we can use it in controllers. EF Core provides us with the AddDbContext extension method.

// Program.cs

var builder = WebApplication.CreateBuilder(args);

// --- EF CORE CONFIGURATION ---
// 1. Read the connection string from JSON
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("Missing ConnectionStrings:DefaultConnection");

// 2. Register the context using SQL Server
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(connectionString);
});

var app = builder.Build();
Copied!

Scoped Lifetime

By default, AddDbContext registers the service as Scoped. Remember what we saw about Dependency Injection? This means an instance of DbContext is created per HTTP request. EF will open and close connections as needed. This is the standard behavior for web databases.

Applying Migrations

Now that ASP.NET knows where the database is and how to connect, we need to create the tables.

Since we have installed the Microsoft.EntityFrameworkCore.Design package, we can use the .NET CLI to generate migrations (the SQL code to create the database).

Run in your terminal:

Create the initial migration (reads your C# code and prepares the SQL)

dotnet ef migrations add InitialCreate

Apply the changes (connects to the database and executes the SQL)

dotnet ef database update

If everything went well, you will see a “Done” message and your database will have been created.

In production, it’s advisable to review or generate the migration script within the deployment process. Automatically running migrations at startup with multiple instances can cause race conditions and make it harder to control a delicate change.

Using the DbContext in the API

Everything is now connected. To read or save data, simply inject the context into your Endpoints or Controllers.

Example in Minimal API

app.MapGet("/productos", async (ApplicationDbContext db) =>
{
    // Use Entity Framework as normal
    return await db.Productos.ToListAsync();
});

app.MapPost("/productos", async (Producto producto, ApplicationDbContext db) =>
{
    db.Productos.Add(producto);
    await db.SaveChangesAsync();
    return Results.Created($"/productos/{producto.Id}", producto);
});
Copied!

Example in Controller

public class ProductosController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    // Inject the context
    public ProductosController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var lista = await _context.Productos.ToListAsync();
        return Ok(lista);
    }
}
Copied!