Skip to content

About

A custom MSBuild task that provides Entity Framework Core scaffolding capabilities for .NET projects.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

EFCore.Scaffolding

An MSBuild task that generates Entity Framework Core models from your database during build time. This package scaffolds your database schema and generates clean, organized C# code with proper namespacing and nullable reference types support.

Installation

<PackageReference Include="AlonSoft.EFCore.Scaffolding" Version="1.0.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

Quick Start

Add a scaffold target to your .csproj file:

<Target Name="ScaffoldEntities" BeforeTargets="CoreCompile" Condition="'$(MY_APP_CONNSTR)' != ''">
    <ScaffoldTask ConnectionString="$(MY_APP_CONNSTR)"
                  OutDir="Entities\Generated"
                  OutFile="Models" />
</Target>

Set your connection string and build:

# Set environment variable (Windows)
$env:MY_APP_CONNSTR = "Server=localhost;Database=MyDatabase;Trusted_Connection=true;"

# Build project
dotnet build

Usage Modes

Type-Per-File Mode (Default)

Generates separate files for each entity (when OutFile is not specified):

<ScaffoldTask ConnectionString="$(ConnectionString)"
              OutDir="Entities\Generated" />

Output: Individual .g.cs files:

  • Entities\Generated\EntityContext.g.cs - DbContext
  • Entities\Generated\User.g.cs - User entity
  • Entities\Generated\Product.g.cs - Product entity
  • etc.

Single File Mode

Creates one consolidated file with all entities:

<ScaffoldTask ConnectionString="$(ConnectionString)"
              OutDir="Entities\Generated"
              OutFile="Models" />

Output: Entities\Generated\Models.g.cs

  • Contains your DbContext class
  • All entity classes
  • Sorted using statements
  • Proper namespace organization

Parameters Reference

Parameter Type Required Default Description
ConnectionString string ✅ - Database connection string
Provider string ❌ SqlServer Database provider: SqlServer, Sqlite, PostgreSql, MySql, Oracle
OutDir string ❌ Entities\Generated Output directory (relative to project)
OutFile string ❌ - Output filename (omit for type-per-file mode)
ContextName string ❌ EntityContext Name of the generated DbContext class
TypeNamePattern string ❌ {Name} Pattern for entity names. Use {Name} placeholder (e.g., {Name}Entity)
UseNullableReferenceTypes bool ❌ true Enable nullable reference types in generated code
UseDataAnnotations bool ❌ true Use data annotations instead of fluent API
Language string ❌ C# Code generation language
ProjectDirectory string ❌ auto-detected Project directory path
RootNamespace string ❌ auto-detected Root namespace for generated code
RawNamespace string ❌ - Override namespace completely

Advanced Configuration

Database Providers

Specify the database provider with the Provider parameter:

<!-- SQL Server (default) -->
<ScaffoldTask ConnectionString="$(ConnectionString)" />

<!-- PostgreSQL -->
<ScaffoldTask ConnectionString="Host=localhost;Database=mydb;Username=user;Password=pass"
              Provider="PostgreSql" />

<!-- MySQL / MariaDB -->
<ScaffoldTask ConnectionString="Server=localhost;Database=mydb;User=user;Password=pass"
              Provider="MySql" />

<!-- SQLite -->
<ScaffoldTask ConnectionString="Data Source=mydb.db"
              Provider="Sqlite" />

<!-- Oracle -->
<ScaffoldTask ConnectionString="Data Source=//localhost/ORCL;User Id=user;Password=pass"
              Provider="Oracle" />

Supported provider aliases:

Provider Aliases
SQL Server SqlServer (default)
PostgreSQL PostgreSql, Postgres, Npgsql
MySQL MySql, MariaDb
SQLite Sqlite
Oracle Oracle

Entity Naming Pattern

Customize generated entity class names with TypeNamePattern:

<!-- Add "Entity" suffix: Customer → CustomerEntity -->
<ScaffoldTask ConnectionString="$(ConnectionString)"
              TypeNamePattern="{Name}Entity" />

<!-- Add "Dto" suffix: Customer → CustomerDto -->
<ScaffoldTask ConnectionString="$(ConnectionString)"
              TypeNamePattern="{Name}Dto" />

<!-- Add prefix: Customer → TblCustomer -->
<ScaffoldTask ConnectionString="$(ConnectionString)"
              TypeNamePattern="Tbl{Name}" />

The pattern must contain exactly one {Name} placeholder.

Custom Namespace

<ScaffoldTask ConnectionString="$(ConnectionString)"
              RootNamespace="MyApp.Data"
              OutDir="Models" />

Skip Scaffolding Conditionally

<PropertyGroup>
    <SkipScaffolding Condition="'$(Configuration)' == 'Debug'">true</SkipScaffolding>
</PropertyGroup>

Environment-Specific Connection Strings

<Target Name="ScaffoldEntities" BeforeTargets="CoreCompile" 
        Condition="'$(ConnectionString)' != '' AND '$(SkipScaffolding)' != 'true'">
    <ScaffoldTask ConnectionString="$(ConnectionString)" />
</Target>

<PropertyGroup Condition="'$(Environment)' == 'Development'">
    <ConnectionString>Server=localhost;Database=MyDevDB;Trusted_Connection=true;</ConnectionString>
</PropertyGroup>

<PropertyGroup Condition="'$(Environment)' == 'Testing'">
    <ConnectionString>Server=testserver;Database=MyTestDB;Trusted_Connection=true;</ConnectionString>
</PropertyGroup>

Generated Code Features

  • Nullable Reference Types: Full support with #nullable enable
  • Namespace Management: Automatic namespace sanitization and organization
  • File Header: Auto-generated headers with nullable context
  • Clean Output: Removes previous generated files before creating new ones
  • Using Statement Optimization: Consolidates and sorts using statements in single-file mode
  • Path Safety: Validates output paths are within project boundaries

Troubleshooting

Common Issues

Build Errors:

  • Ensure .NET 9.0 SDK is installed
  • Clear NuGet caches: dotnet nuget locals all --clear
  • Check connection string format

Path Issues:

  • OutDir must be relative to project root
  • Cannot use paths outside project directory
  • Use forward slashes or escaped backslashes in MSBuild

Database Connection:

  • Verify connection string is correct
  • Ensure database server is accessible
  • Check SQL Server authentication mode

Error Messages

  • "OutDir must be relative to the project": Use relative paths only
  • "Cannot determine the project directory": Pass ProjectDirectory="$(MSBuildProjectDirectory)"
  • "OutDir cannot be the project root": Choose a subfolder for output

Requirements

  • .NET 8.0+ SDK (task runs on .NET 9.0 runtime, but your project can target .NET 8.0+)
  • Entity Framework Core 9.0+
  • MSBuild 17.0+
  • Supported databases: SQL Server, PostgreSQL, MySQL/MariaDB, SQLite, Oracle

License

This project is licensed under the MIT License.

About

A custom MSBuild task that provides Entity Framework Core scaffolding capabilities for .NET projects.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages