Generate an EF Core model from an existing SQL Server database

For a database-first application, EF Core can generate entity types and a DbContext from an existing schema. This replaces the old SQLMetal/DBML generation workflow for a new EF Core application. It does not convert an existing LINQ-to-SQL application automatically.

Start with a narrow table selection and inspect the resulting relationships before committing generated files.

Install matching tools

Requires .NET 10, access to a SQL Server database, and a schema containing dbo.Items. Run from a new console project directory:

Plain text
dotnet new console -n ScaffoldDemo -f net10.0
cd ScaffoldDemo
dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.0
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.0
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.0

Use a nonsecret integrated-authentication connection string for this local example, substituting your server and database:

Plain text
dotnet ef dbcontext scaffold "Server=localhost;Database=Demo;Integrated Security=True;Encrypt=True" Microsoft.EntityFrameworkCore.SqlServer --table dbo.Items --context DemoContext --output-dir Models --context-dir Data --no-onconfiguring

The expected result is an entity file and Data/DemoContext.cs. A certificate trusted by the client must cover the server name. For password-based deployments, use the supported configuration/name-based connection mechanism rather than putting a password in command history.

Review before using the model

--no-onconfiguring prevents generation of a hard-coded connection in the context. Supply DbContextOptions<DemoContext> from application configuration at runtime. Inspect primary keys, nullable columns, generated values and relationships against the real schema.

Keep custom behavior in partial classes or separate configuration. Re-scaffolding with --force can overwrite generated files. Review a fresh generation rather than treating it as a migration. Scaffolding reads the existing schema and does not create or update the database.

Official references

Reverse Engineering - EF Core
Reverse engineering a model from an existing database using Entity Framework Core
https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/
EF Core reverse engineering

Author: Herman Schoenfeld