Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Migrations

Scaffolding an Existing Database (Database First)

Generate entity classes and a DbContext from an existing database with dotnet ef dbcontext scaffold, customize the output with partial classes, and re-scaffold safely.

Migrations are code first: the C# model is the source of truth and the database follows. Often the opposite is true. A company database already exists, with years of tables, views and stored procedures, and many applications depend on it. In that case you use database first: EF Core reads the schema and generates the C# model for you. This is called scaffolding or reverse engineering.

The real tool needs a database, so commands and generated code are read-only. The runnable stand-in models what the scaffolder does: it turns a schema description into class text.

The command

TEXT
dotnet ef dbcontext scaffold "Data Source=legacy.db" Microsoft.EntityFrameworkCore.Sqlite
    --output-dir Models
    --context-dir Data
    --context LegacyContext
    --data-annotations
    --force

The arguments are the connection string and the provider package. The most useful options:

Option Meaning
--output-dir Folder for entity classes
--context-dir, --context Folder and name of the generated context
--table Customers --table Orders Only these tables
--schema sales Only this schema (SQL Server, PostgreSQL)
--data-annotations Use attributes where possible instead of only fluent API
--use-database-names Keep database names instead of converting to C# style
--no-onconfiguring Do not embed the connection string in the context
--no-pluralize Keep singular/plural names as they are
--force Overwrite existing files

Pass the connection string through a user secret or --connection name in real projects (Name=ConnectionStrings:Legacy), never as text committed to source control.

What you get

For a Customers table with a nullable Email column and an Orders table with a foreign key, the scaffolder writes something like this:

C#
public partial class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public string? Email { get; set; }
    public virtual ICollection<Order> Orders { get; set; } = new List<Order>();
}

public partial class LegacyContext : DbContext
{
    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>(entity =>
        {
            entity.HasIndex(e => e.Email, "IX_Customers_Email").IsUnique();
            entity.Property(e => e.Name).HasMaxLength(100);
        });

        modelBuilder.Entity<Order>(entity =>
        {
            entity.HasOne(d => d.Customer).WithMany(p => p.Orders)
                  .HasForeignKey(d => d.CustomerId);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Several details are worth noticing:

  • Classes are partial, and the context has a partial void OnModelCreatingPartial. These are your extension points.
  • Nullable columns become nullable properties; non-nullable strings get = null!.
  • Foreign keys become navigation properties both ways.
  • Everything the schema says (lengths, indexes, unique, default values) appears as fluent configuration.

Never edit generated files

If you edit Customer.cs and later re-scaffold with --force, your changes vanish. Put your own code in separate partial files:

C#
// Customer.Extra.cs (yours, safe from re-scaffolding)
public partial class Customer
{
    public string DisplayName => Email is null ? Name : $"{Name} <{Email}>";
}

// LegacyContext.Extra.cs
public partial class LegacyContext
{
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().HasQueryFilter(c => !c.IsDeleted);
    }
}

For extra behavior on a table you do not want to change, you can also write a custom scaffolding template (dotnet new ef-templates creates editable T4 templates), but partial classes cover most needs.

Scaffolding does not run migrations. If you later want to evolve this database with migrations, scaffold once, create an initial migration, and then edit the generated Up to be empty (or ignore it with database update --connection on a fresh copy). Many teams keep a legacy database owned by SQL scripts and only use EF Core to read and write it.

Views, keyless types and what is not scaffolded

  • Tables without a primary key and views are scaffolded as keyless entity types (HasNoKey()), which you can query but not update.
  • Stored procedures are not mapped to classes; call them with FromSql (see Bulk Operations and Raw SQL).
  • Triggers, check constraints and sequences are in the database but not described in C#.

When to choose database first

Code first or database first?

Code first New project, you own the schema
Database first Existing schema, others own it
Hybrid Scaffold once, then migrate

Pick one owner of the schema

1 / 2

The rule is one owner of the schema. If the DBA team changes the database, scaffold again. If your app changes it, use migrations. Two owners generate drift.

Stand-in: a tiny scaffolder

This stand-in is not EF Core. It reads a schema description (a list of columns) and generates a C# class, mapping SQL types to C# types and nullability to ?, which is the heart of scaffolding.

C# Stand-in: generate a class from a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that full_name became FullName. The real scaffolder does the same naming conversion unless you pass --use-database-names.

Stand-in: partial classes keep your code

C# Stand-in: partial classes survive re-scaffolding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does dotnet ef dbcontext scaffold produce?

    Scaffolding reverse-engineers the schema into a C# model.
  2. 2. Where should you put your own members for a scaffolded Customer class?

    Scaffolded classes are partial so your additions survive when you re-scaffold with --force.
  3. 3. How are views and tables without a primary key scaffolded?

    Keyless types (HasNoKey) are read-only entry points for data without a key.
  4. 4. What is the main risk of mixing migrations and scaffolding on the same database?

    Choose one owner: either the database team (scaffold again after changes) or your app (migrations).

Summary

  • dotnet ef dbcontext scaffold <connection> <provider> generates entities and a context from an existing schema.
  • Use options such as --table, --data-annotations and --no-onconfiguring to shape the result.
  • Scaffolded types are partial: put your code in separate files so re-scaffolding is safe.
  • Views and key-less tables become keyless types; stored procedures need FromSql.
  • Decide who owns the schema: code first with migrations, or database first with scaffolding.

Next: LINQ to Entities: Writing Queries