无权限修改的遗留数据库迁移至Entity Framework Core的正确方案咨询
Hey there! This is a really common scenario when dealing with legacy or admin-managed databases, and I’m happy to say EF Core has solid tools to handle it—though the workflow is a bit different from the old EDMX days in EF6. Let’s break down your questions one by one:
Absolutely! EF Core’s take on Database First is called reverse engineering, and it’s built exactly for cases where you don’t control the database schema. It replaces the EF6 EDMX designer with command-line/PMC scaffolding, but it achieves the same core goal: generating entity models and a DbContext from an existing database.
You’ll use the Scaffold-DbContext command (either in the Package Manager Console or .NET CLI) to create your initial models. Here are the basics:
Package Manager Console (PMC)
Scaffold-DbContext "Server=your-server;Database=your-db;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context YourDbContextName
.NET CLI
dotnet ef dbcontext scaffold "Server=your-server;Database=your-db;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer --output-dir Models --context YourDbContextName
Useful parameters to tailor the output:
-Tables Table1,Table2: Only scaffold specific tables (instead of the entire database)-DataAnnotations: Use data annotations (like[Required]) instead of Fluent API for configuration-NoPluralize: Disable automatic pluralization of entity names (helpful if you want to match your domain model naming conventions)-Force: Overwrite existing model files (use this when syncing database changes, but read the next section first!)
When your admin updates the database (adds tables, modifies columns, etc.), you have two reliable ways to keep your models in sync:
1. Manual Updates (for small, isolated changes)
If the admin only adds a single field or makes a minor tweak, you can manually update the corresponding entity class. For example, if they add a LastLoginDate column to the Users table, just add:
public DateTime? LastLoginDate { get; set; }
to your User entity class. This is fast for small changes but risks human error if you miss details like data constraints.
2. Re-Run Scaffolding (for larger changes)
For bigger updates (multiple new fields, new tables, changed data types), re-running the scaffolding command with the -Force parameter is the most trustworthy way to sync. This regenerates all your model files to match the latest schema.
Critical Rule: Never modify the scaffolded files directly. Instead:
- Use partial classes to add custom logic/properties to entities. If scaffolding generates
public partial class User { ... }, create a separate fileUser.Custom.cswith:
This file won’t be touched when you re-scaffold.public partial class User { // Your custom property/method here public string FullName => $"{FirstName} {LastName}"; } - Use the
OnModelCreatingPartialmethod for DbContext customizations. The scaffolded DbContext is a partial class with an emptyOnModelCreatingPartialmethod. Create a separate fileYourDbContext.Custom.csto override it:
This lets you keep your domain model naming clean while mapping to the database’s conventions—without losing changes when re-scaffolding.public partial class YourDbContext { partial void OnModelCreatingPartial(ModelBuilder modelBuilder) { // Your custom Fluent API config here (e.g., map domain names to database columns) modelBuilder.Entity<User>() .Property(u => u.UserId) .HasColumnName("user_id"); } }
It’s your call based on the change size:
- For small, single-field changes: Yes, you can manually add the field to the entity class for speed.
- For larger or multiple changes: No, re-run scaffolding with
-Force—it will add the new field automatically. Just ensure your customizations are in partial classes to avoid losing work.
Only if you’ve edited the scaffolded files directly. If you use partial classes for customizations, those changes are completely safe—re-scaffolding only overwrites the files generated by the command.
To add an extra layer of safety:
- Use version control (Git) to track changes. Commit your work before re-scaffolding, then review the diffs afterward to confirm only database-related changes are applied.
- Avoid renaming properties in scaffolded files. Instead, use the
OnModelCreatingPartialmethod to map your domain-friendly property names to the database’s column names—this keeps your model clean and preserves your changes through re-scaffolding.
内容的提问来源于stack exchange,提问作者Ghini Antonio

