如何将Scaffold-DbContext生成的DbContext类定向到指定项目文件夹?
Absolutely! You can split your generated models and DbContext into separate projects (Backend for models, DbContexts for the context and migrations) using the Scaffold-DbContext tool. Here's a straightforward breakdown to make this work:
1. Use Targeted Command Parameters
Whether you’re using the Package Manager Console (PMC) in Visual Studio or the .NET CLI, you can explicitly define separate locations for your models and DbContext.
Package Manager Console Command
Run this in PMC (adjust names to match your project setup):
Scaffold-DbContext "YourDatabaseConnectionString" Microsoft.EntityFrameworkCore.SqlServer ` -OutputDir Models ` -Project Backend ` -Context AppDbContext ` -ContextDir . ` -Project DbContexts ` -Force
Let’s break down each parameter:
-OutputDir Models: Places model classes in theModelsfolder of your Backend project-Project Backend: Explicitly sets the Backend project as the output destination for models-Context AppDbContext: Names your DbContext class (replace with your preferred name)-ContextDir .: Puts the DbContext directly in the root of the DbContexts project; use-ContextDir Dataif you want it in a subfolder likeDbContexts/Data-Project DbContexts: Tells the tool to generate the DbContext in this project instead of the model project-Force: Overwrites existing files (use this if re-scaffolding to update models/context)
.NET CLI Command
If you prefer working outside Visual Studio, run this from your solution root:
dotnet ef dbcontext scaffold "YourDatabaseConnectionString" Microsoft.EntityFrameworkCore.SqlServer ` --output-dir Models ` --project Backend/Backend.csproj ` --context AppDbContext ` --context-dir . ` --project DbContexts/DbContexts.csproj ` --force
2. Critical Pre-Requisites
Before running the command, confirm these details:
- The DbContexts project must reference the Backend project (the DbContext needs access to your model classes)
- Install required NuGet packages:
- Backend: At minimum,
Microsoft.EntityFrameworkCore - DbContexts:
Microsoft.EntityFrameworkCore,Microsoft.EntityFrameworkCore.Design, and your database provider package (e.g.,Microsoft.EntityFrameworkCore.SqlServer)
- Backend: At minimum,
3. Managing Migrations
Since your DbContext lives in the DbContexts project, target it when running migration commands. For example, to add an initial migration:
Add-Migration InitialCreate -Project DbContexts -StartupProject Backend
Or via CLI:
dotnet ef migrations add InitialCreate --project DbContexts/DbContexts.csproj --startup-project Backend/Backend.csproj
This keeps all migration files neatly in the DbContexts project, aligning perfectly with your repository pattern structure.
内容的提问来源于stack exchange,提问作者Aldemar Cuartas Carvajal

