skip to content

With the dotnet-ef tool, what does dotnet ef dbcontext scaffold generate from an existing database, and which options and habits keep a re-scaffold from destroying your changes?

level: middleimportance: should knowfreq 42%

answer

  1. connection string, then provider package id
  2. partial classes + OnModelCreatingPartial
  3. --use-database-names, --data-annotations
  4. Name=ConnectionStrings:... or --no-onconfiguring
  5. --force overwrites; ef-templates customises

basics

~20 s

dotnet ef dbcontext scaffold reads a database schema and writes partial entity classes plus a partial DbContext configured with the fluent API. Edits survive a re-scaffold only in separate partial files or OnModelCreatingPartial, because --force overwrites generated files.

solid answer

~40 s

`dotnet ef dbcontext scaffold "<connection>" Npgsql.EntityFrameworkCore.PostgreSQL` needs `Microsoft.EntityFrameworkCore.Design` and the provider package in the project. It writes one partial class per table or view and a partial context whose `OnModelCreating` holds fluent configuration and calls the partial `OnModelCreatingPartial`. `-o`, `-c`, `--context-dir`, `-t` and `--schema` control output and scope; `--data-annotations` uses attributes where possible; `--use-database-names` keeps names such as `TTL_NM` instead of `TtlNm`; `--no-pluralize` disables the pluralizer. By default the connection string lands in `OnConfiguring` behind a `#warning`; pass `Name=ConnectionStrings:Bookstore` or `--no-onconfiguring` instead. Existing files are not overwritten without `--force`, which overwrites everything, so keep additions in other partial files, or customise generation with T4 templates from `dotnet new ef-templates`.

code

csharp · 16 lines
csharp
// Data/BookstoreContext.Custom.cs - never touched by a re-scaffold
public partial class BookstoreContext
{
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BkTitle>()
            .Property(t => t.TtlNm)
            .HasMaxLength(250); // overrides the generated HasMaxLength(200)
    }
}

// Data/Entities/BkTitle.Custom.cs
public partial class BkTitle
{
    public bool IsBackList => PubDt < DateOnly.FromDateTime(DateTime.Today).AddYears(-2);
}

go deeper

for a junior

Recall the two required arguments, connection string and provider package id, and that the command writes entity classes plus a context.

for a middle

Explain the main options, including --use-database-names, --data-annotations, --no-onconfiguring and --force, and what the generated OnModelCreating contains.

for a senior

Set up a re-scaffold-safe workflow with partial classes, OnModelCreatingPartial and Name= connection strings, or T4 templates for systematic changes.

for a principal

Decide whether a legacy database stays database-first with repeated scaffolding or moves to migrations, based on who owns the schema.

## What scaffolding is **Scaffolding** (reverse engineering) builds an EF Core model from an existing database instead of from code. For a legacy bookstore database it is usually the first step: generate the entity classes and context, then decide whether to keep re-scaffolding as the database changes or switch to code-first migrations. Prerequisites in the target project: - the **`Microsoft.EntityFrameworkCore.Design`** package; - the **provider** package, here `Npgsql.EntityFrameworkCore.PostgreSQL`; - the `dotnet ef` command available on the machine. ## The command ```bash dotnet ef dbcontext scaffold "Name=ConnectionStrings:Bookstore" Npgsql.EntityFrameworkCore.PostgreSQL \ --context BookstoreContext --context-dir Data --output-dir Data/Entities \ --schema legacy --table public.bk_titles --no-onconfiguring ``` The two required arguments are the **connection string** and the **provider**. The main options: | Option | Effect | |---|---| | `-o`, `--output-dir` | Folder for entity classes | | `-c`, `--context` / `--context-dir` | Context class name and folder | | `-n`, `--namespace` / `--context-namespace` | Namespaces for the generated code | | `-t`, `--table` (repeatable) | Only these tables or views; `schema.table` form allowed | | `--schema` (repeatable) | Every table and view in these schemas | | `-d`, `--data-annotations` | Use attributes where possible instead of fluent API only | | `--use-database-names` | Keep table and column names as in the database | | `--no-pluralize` | Turn off the pluralizer | | `--no-onconfiguring` | Do not generate `OnConfiguring` | | `-f`, `--force` | Overwrite existing files | ## What it generates - One **`partial` class per table or view**. By default names are fixed up to .NET conventions, so a table `BK_TITLES` with a column `TTL_NM` becomes a class like `BkTitle` with a property `TtlNm`; `--use-database-names` keeps the original names as far as they are valid identifiers. - A **`partial` context** with a `DbSet<T>` per entity and an `OnModelCreating` full of **fluent API** configuration: `ToTable`, `HasColumnName`, `HasMaxLength`, keys, composite indexes with `HasDatabaseName`, and relationships. With `--data-annotations`, the parts that attributes can express move onto the classes. - A call to the partial method **`OnModelCreatingPartial(modelBuilder)`** at the end of `OnModelCreating`, which you implement in your own file. - Unless told otherwise, an **`OnConfiguring`** containing the literal connection string, preceded by a `#warning` telling you to move it out of source code. ## Keeping secrets out of generated code Two approaches avoid the embedded connection string: 1. Pass **`Name=ConnectionStrings:Bookstore`** as the connection argument. The tools read the value from the project's configuration, such as user secrets, and the generated `OnConfiguring` uses the name rather than the secret. 2. Pass **`--no-onconfiguring`** and supply options from the application's own registration. ## Surviving a re-scaffold By default the command **refuses to overwrite** existing files. `--force` overwrites them all, discarding any edits. If you plan to re-scaffold whenever the database changes: - **never edit generated files**; - put extra members, computed properties and interfaces in a **separate partial class file** for each entity; - put model tweaks in your own **`OnModelCreatingPartial`** implementation, which runs after the generated configuration and therefore overrides it; - if every generated class needs the same change, **customise the generator** instead: `dotnet new install Microsoft.EntityFrameworkCore.Templates`, then `dotnet new ef-templates` adds `CodeTemplates/EFCore/DbContext.t4` and `EntityType.t4` to the project, and the scaffolder uses them. The alternative is to **scaffold once**, then treat the code as yours and evolve the schema with migrations. Mixing the two, editing generated files and re-scaffolding later, is where work gets lost. ## Reviewing the generated model Scaffolded code is a faithful copy of the schema, which is not always the model you want. Check: - **keys and indexes**: composite indexes appear as `HasIndex(e => new { e.AuthId, e.PubDt }, "IX_TITLES_AUTH_PUB")`, and tables without a primary key are generated as keyless entities; - **lengths and types**: every `varchar(40)` becomes `HasMaxLength(40)`, which is correct but noisy; pre-convention configuration can express a shared default afterwards; - **relationships**: foreign keys become navigations, with names synthesised from the columns; - **views and key-less tables**: views are mapped with `ToView`, and any table or view without a primary key becomes a keyless entity configured with `HasNoKey()`. ## Pitfalls - Forgetting the Design package, so the tool cannot run the scaffolder. - Scaffolding with a privileged production login when a read-only account would do. - Re-scaffolding with `--force` after hand-editing generated classes. - Expecting `--use-database-names` to keep everything: invalid identifiers and synthesised navigation names are still fixed up.

  • Why does the generated OnConfiguring carry a #warning, and how do you avoid it?
    By default the scaffolder writes the connection string you passed into `OnConfiguring`, and the `#warning` reminds you that it may contain a password in source code. Pass `Name=ConnectionStrings:Bookstore` so the generated code reads it from configuration, or `--no-onconfiguring` to omit the method and configure options elsewhere.
  • When would you scaffold once and switch to migrations instead of re-scaffolding?
    When the application team will own the schema from now on. After one scaffold, the classes become normal code, you edit them freely, and `dotnet ef migrations add` evolves the database. Re-scaffolding fits when another team or system owns the schema and your model must follow it.

  • Scaffolding merges database changes into your hand-edited entity classes.
  • --no-pluralize keeps the original database column names.
  • --force only overwrites files that have not been edited.
  • The scaffolded context stores the connection string safely in configuration by default.
  • Scaffolding needs only the provider package, nothing else.