You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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.Design
    • Microsoft.EntityFrameworkCore.SqlServer (replace with your database provider if not using SQL Server)
    • Microsoft.Extensions.DependencyInjection
  • Customization: Adjust the ReverseEngineeringOptions to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:52:52