基于Rowan Miller文章,如何通过代码使用EF Core 2.1脚手架系统?
Programmatically Using EF Core's Scaffolding System
If you want to leverage EF Core's scaffolding functionality directly in code (instead of relying on CLI tools), here's a practical implementation based on Rowan Miller's work. This approach lets you generate entity classes and a DbContext from an existing database programmatically, giving you more control over the process.
Step-by-Step Implementation
First, set up the necessary services and retrieve the scaffolding generator:
// Add core scaffolding services var serviceCollection = new ServiceCollection() .AddScaffolding() .AddLogging(); // Configure SQL Server design-time services (swap with your provider if needed) var provider = new SqlServerDesignTimeServices(); provider.ConfigureDesignTimeServices(serviceCollection); // Build the service provider and get the generator var serviceProvider = serviceCollection.BuildServiceProvider(); var generator = serviceProvider.GetService<ReverseEngineeringGenerator>(); // Define scaffolding options (customize these to your needs) var options = new ReverseEngineeringOptions { ConnectionString = "Your_SQL_Server_Connection_String", Schemas = new[] { "dbo" }, // Target specific schemas Tables = new[] { "Customer", "Order" }, // Target specific tables ContextClassName = "AppDbContext", OutputDir = Path.Combine(Directory.GetCurrentDirectory(), "Models"), UseDataAnnotations = true // Toggle between DataAnnotations or Fluent API }; // Execute the scaffolding process await generator.GenerateAsync(options);
Key Notes to Keep in Mind
- Required NuGet Packages: Ensure you have these installed in your project:
Microsoft.EntityFrameworkCore.DesignMicrosoft.EntityFrameworkCore.SqlServer(replace with your database provider if not using SQL Server)Microsoft.Extensions.DependencyInjection
- Customization: Adjust the
ReverseEngineeringOptionsto exclude/include tables, set naming conventions, choose between DataAnnotations or Fluent API, and specify output paths. - Logging: The added logging service helps debug issues like missing permissions, invalid connection strings, or database schema mismatches during scaffolding.
内容的提问来源于stack exchange,提问作者HamedFathi
相关产品推荐
相关产品推荐

