Este guia descreve o processo completo de configuração da Connection String, configuração do DbContext, criação e aplicação de Migrations usando Entity Framework Core com SQL Server 2025 em Docker.
Configurar a Connection String no appsettings.json
Definir a String de Conexão apontando explicitamente para o IP, evitando dependência de resolução de localhost.
Após a criação do builder, configurar o DbContext utilizando a Connection String definida no appsettings.json:
Com isso, o AppDbContext passar a estar disponível para injeção de dependência em toda a aplicação.
Limpar e reconstruir o projeto
Antes de criar as migrations, limpar e reconstruir o projeto para garantir que não exista lixo de build.
Comandos:
Exemplo de execução:
Saída esperada: build construído com êxito.
Verificar se o SQL Server está em execução no Docker
Considerando que o SQL Server foi configurado previamente em Docker, é necessário verificar se o container está ativo.
Será iniciado o processo de migração e para isso o banco de dados precisa estar sendo executado. Considerando que o banco de dados está sendo executado em Docker e foi configurado anteriormente no início do projeto, verificar se ele está sendo executado, se ele existe, caso esteja parado inicia-lo, verificar sua execução.
Caso o container esteja parado, inicia-lo:
Adicionar ao Migrations com a execução de dotnet ef migrations add
O container deve estar exposto na porta 1433.
Criar a migration inicial
Com o banco em execução e o projeto compilando corretamente, criar a migration:
Exemplo de execução:
Após a execução será criado o diretório Migrations, contendo os seguintes arquivos:
AppDbContextModelSnapshot
YYYYMMDDHHMMSS_v1
Atualizar a ferramenta dotnet-ef
Caso apareça o aviso de versão entre runtime e ferramentas, atualize o dotnet-ef com os comandos:
Aviso:
Exemplo de atualização do dotnet-ef:
A versão deve corresponder ao runtime utilizado.
Validar conexão com o SQL Server via sqlcmd
Para validar conectividade e TLS, utilize o sqlcmd:
Exemplo de execução com execução de comando simples:
Isso confirma conectividade, autenticação e criptografia.
> wsl
~$ docker container ls | grep 2025
~$ docker container ls -a | grep 2025
9dc633ab7148 mcr.microsoft.com/mssql/server:2025-latest "/opt/mssql/bin/laun…" 16 hours ago Exited (137) 32 seconds ago sqlserver2025
~$ docker container start 9dc633ab7148
9dc633ab7148
~$ docker container ls | grep 2025
9dc633ab7148 mcr.microsoft.com/mssql/server:2025-latest "/opt/mssql/bin/laun…" 16 hours ago Up 5 seconds 0.0.0.0:1433->1433/tcp, :::1433->1433/tcp sqlserver2025
PS C:\dev\RepositoryStore> dotnet ef migrations add v1
Build started...
Build succeeded.
The Entity Framework tools version '9.0.2' is older than that of the runtime '10.0.0'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
Done. To undo this action, use 'ef migrations remove'
dotnet ef migrations add v1
PS C:\dev\RepositoryStore> dotnet ef migrations add v1
Build started...
Build succeeded.
The Entity Framework tools version '9.0.2' is older than that of the runtime '10.0.0'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
Done. To undo this action, use 'ef migrations remove'
PS C:\dev\RepositoryStore> dotnet tool update --global dotnet-ef
A ferramenta 'dotnet-ef' foi atualizada com êxito da versão '9.0.2' para a versão '10.0.0'.
PS C:\dev\RepositoryStore> dotnet ef --version
Entity Framework Core .NET Command-line Tools
10.0.0
dotnet tool update --global dotnet-ef
dotnet ef --version
The Entity Framework tools version '9.0.2' is older than
that of the runtime '10.0.0'.
Update the tools for the latest features and bug fixes.
See https://aka.ms/AAc1fbw for more information.
PS C:\dev\RepositoryStore> dotnet tool update --global dotnet-ef
A ferramenta 'dotnet-ef' foi atualizada com êxito da versão '9.0.2'
para a versão '10.0.0'.
PS C:\dev\RepositoryStore> dotnet ef --version
Entity Framework Core .NET Command-line Tools
10.0.0
sqlcmd.exe -S localhost,1433 -U sa -P Sql@2025Secure! -C -N
PS C:\Dev\RepositoryStore> sqlcmd.exe -S localhost,1433 -U sa -P Sql@2025Secure! -C -N
1> SELECT @@VERSION
2> GO
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2025 (RTM) - 17.0.1000.7 (X64)
Oct 21 2025 12:05:57
Copyright (C) 2025 Microsoft Corporation
Enterprise Developer Edition (64-bit) on Linux (Ubuntu 22.04.5 LTS) <X64>
(1 row affected)
1>
dotnet ef database update
PS C:\Dev\RepositoryStore> dotnet ef database update
Build started...
Build succeeded.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (505ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
CREATE DATABASE [repository-pattern];
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (374ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [repository-pattern] SET READ_COMMITTED_SNAPSHOT ON;
END;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1
info: Microsoft.EntityFrameworkCore.Migrations[20411]
Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (25ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @result int;
EXEC @result = sp_getapplock @Resource = '__EFMigrationsLock', @LockOwner = 'Session', @LockMode = 'Exclusive';
SELECT @result
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (9ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (27ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];
info: Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20251207144811_v1'.
Applying migration '20251207144811_v1'.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Product] (
[Id] int NOT NULL IDENTITY,
[Title] NVARCHAR(160) NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY ([Id])
);
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N'20251207144811_v1', N'10.0.0');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @result int;
EXEC @result = sp_releaseapplock @Resource = '__EFMigrationsLock', @LockOwner = 'Session';
SELECT @result
Done.