joelmartinez/chimpiler

C#

0

60 commits

updated Aug 29, 2026

See the code

README

Chimpiler

A multi-purpose CLI tooling ecosystem for .NET.

Overview

Chimpiler is an extensible CLI framework designed to provide pragmatic tooling for modern .NET applications and development workflows.

Features

chimpiler clawcker — OpenClaw Instance Manager

Clawcker makes it trivially easy to create, run, and access local OpenClaw instances using Docker. Get started with just three commands:

chimpiler clawcker new myagent
chimpiler clawcker start myagent
chimpiler clawcker talk myagent

Key Features:

  • ✅ One-command instance creation
  • ✅ Automatic Docker image pulling
  • ✅ Secure random token generation
  • ✅ Persistent configuration and workspace
  • ✅ Easy web UI access
  • ✅ Multiple instance management

Learn more about Clawcker →

chimpiler ef-migrate — EF Core Model → DACPAC Generator

The ef-migrate command generates one or more DACPAC files from EF Core DbContext models defined in a compiled .NET assembly. Each DbContext represents a distinct database, and the tool emits one DACPAC per DbContext without requiring:

  • A live database connection
  • Existing EF Core migrations
  • Manual SQL scripting
  • Database import/export workflows

Key Benefits:

  • ✅ Fully automated, CI-friendly workflow
  • ✅ Model-driven schema generation
  • ✅ DACPAC artifacts compatible with SqlPackage and Azure DevOps
  • ✅ Deterministic and repeatable output
  • ✅ No dependency on SQL Server during build

Learn more about ef-migrate →

chimpiler dacpac apply — DACPAC → PostgreSQL Schema Deployment

The dacpac apply command reads SQL Server Database Project DACPACs through public DacFx APIs and translates a deliberately limited, validated subset into PostgreSQL DDL.

export CHIMPILER_DACPAC_CONNECTION_STRING='Host=localhost;Database=app;Username=app;Password=...'
chimpiler dacpac apply ./Database.dacpac --dry-run
chimpiler dacpac apply ./Database.dacpac

Safety and deployment behavior:

  • ✅ Deterministic state-based planning with no rename inference
  • ✅ PostgreSQL catalog introspection, transaction rollback, and advisory locking
  • ✅ Dry-run and reviewable script output
  • ✅ Destructive operations blocked unless --allow-destructive is supplied
  • ✅ Unsupported objects, expressions, and DACPAC deployment scripts rejected before connecting
  • ✅ Provider-neutral library boundary for future MySQL support

This is not SqlPackage for PostgreSQL. Chimpiler independently implements the PostgreSQL planner and executor and uses DacFx only to read the package model through public APIs.

Learn more about dacpac apply →

chimpiler kb — Local GraphRAG Knowledge Base

The kb command builds and queries a completely local, zero-cloud, zero-Python knowledge base stored in a single SQLite file. It is designed for local CLI and agent harness use: agents can retrieve direct evidence, then maintain a focused, evidence-backed graph of entities and relationships using the agent's own reasoning.

chimpiler kb init
chimpiler kb add ./docs
chimpiler kb graph-search "how do I generate a dacpac?"

Key Features:

  • ✅ SQLite is the only database — no server, no Python, no cloud
  • ✅ Local ONNX embedding models, downloaded on first use
  • ✅ Vectors and a lightweight knowledge graph in the same file
  • ✅ Semantic search plus bounded traversal of agent-authored evidence relationships
  • ✅ Agent-ready prompt, entity registration, and evidence-bearing relationship enrichment
  • ✅ Pluggable IEmbeddingProvider for future cloud providers

Learn more about kb →

Give a local agent this prompt

Copy this into a local/CLI agent harness before asking it to use a knowledge base:

Use Chimpiler's local KB as your knowledge-retrieval tool.

If `chimpiler` is not available, install it with:
dotnet tool install --global Chimpiler --add-source https://api.nuget.org/v3/index.json --ignore-failed-sources

Then run:
chimpiler kb prompt

Follow that output. Use `chimpiler kb search` for direct evidence. Delegate distinct source themes
to subagents when useful, returning only cited entity/relationship candidates to the orchestrator.
Register only verified entities and relationships, then use `chimpiler kb graph-search --depth 2`
to follow those focused evidence links. Depth is relationship hops; inspect each returned `trail:`
and cited source before treating a `(graph)` result as evidence.

Installation

As a .NET Global Tool

Install Chimpiler globally using the .NET CLI:

dotnet tool install -g Chimpiler

To update to the latest version:

dotnet tool update -g Chimpiler

If a configured package mirror reports an older version or the installed CLI lacks kb, use NuGet.org explicitly:

dotnet tool update -g Chimpiler --add-source https://api.nuget.org/v3/index.json --ignore-failed-sources
chimpiler kb --help

After installation, run chimpiler kb prompt for concise instructions that can be injected into a local agent's context.

From Source

git clone https://github.com/joelmartinez/chimpiler.git
cd chimpiler
dotnet build
dotnet pack src/Chimpiler/Chimpiler.csproj -c Release
dotnet tool install -g --add-source ./src/Chimpiler/bin/Release Chimpiler

Usage

Basic Usage

Generate DACPACs for all DbContexts in an assembly:

chimpiler ef-migrate --assembly path/to/YourApp.dll

Preview applying a DACPAC to PostgreSQL:

chimpiler dacpac apply path/to/Database.dacpac \
  --provider postgresql \
  --connection-string "$CHIMPILER_DACPAC_CONNECTION_STRING" \
  --dry-run

Write a reviewable script without changing the target:

chimpiler dacpac apply path/to/Database.dacpac --script ./deployment.sql

This will discover all DbContext types in the assembly and generate a DACPAC for each in the ./output directory.

Specify a Single DbContext

Generate a DACPAC for a specific DbContext:

chimpiler ef-migrate --assembly path/to/YourApp.dll --context YourNamespace.OrdersDbContext

Custom Output Directory

chimpiler ef-migrate --assembly path/to/YourApp.dll --output ./dacpacs

Enable Verbose Logging

chimpiler ef-migrate --assembly path/to/YourApp.dll --verbose

Command Reference

dacpac apply

Apply a supported DACPAC schema subset to PostgreSQL.

OptionRequiredDescriptionDefault
<dacpac>✅Path to the DACPAC-
--provider❌Target provider (postgresql; MySQL reserved for future support)postgresql
--connection-string✅*Target connection stringCHIMPILER_DACPAC_CONNECTION_STRING
--dry-run❌Print the plan and roll backfalse
--script <path>❌Write the plan and roll back-
--allow-destructive❌Permit reviewed destructive operationsfalse

* Required through either the option or environment variable.

ef-migrate

Generate DACPACs from EF Core DbContext models.

Options:

OptionAliasRequiredDescriptionDefault
--assembly-a✅Path to compiled .NET assembly containing DbContext types-
--context-c❌Fully qualified type name of a specific DbContextAll DbContexts
--output-o❌Output directory for generated DACPACs./output
--framework-f❌Target framework hint for multi-targeted assemblies-
--verbose-v❌Enable detailed loggingfalse

DACPAC Naming

DACPAC files are named based on the DbContext type name with the following rules:

  1. Strip the Context suffix if present
  2. Strip the DbContext suffix if present
  3. Append .dacpac

Examples:

DbContext TypeDACPAC Filename
TheDatabaseContextTheDatabase.dacpac
OrdersDbContextOrders.dacpac
ReportingContextReporting.dacpac
InventoryContextInventory.dacpac

How It Works

  1. Assembly Loading — The tool loads the target assembly via reflection
  2. DbContext Discovery — Discovers all types inheriting from DbContext
  3. Model Extraction — For each DbContext:
    • Instantiates the context
    • Builds the EF Core runtime model
    • Extracts relational metadata (tables, columns, keys, indexes, schemas)
  4. DACPAC Generation — Translates the EF Core model into SQL Server schema objects using DacFx APIs
  5. File Output — Writes each DACPAC to the output directory

Comparison to Alternatives

vs. EF Core Migrations

FeatureChimpiler ef-migrateEF Core Migrations
ApproachState-based (DACPAC)Migration-based
Output.dacpac filesC# migration files
Database Required❌ No❌ No
DeploymentSqlPackage / Azure DevOpsdotnet ef database update
Change TrackingHandled by SqlPackageHandled by EF Core
ReversibilityVia DACPAC snapshotsVia down migrations

When to use Chimpiler:

  • You prefer state-based deployments
  • You want DACPAC artifacts for CI/CD
  • You're prototyping and need fast iteration

When to use EF Migrations:

  • You need custom migration logic
  • You want version-controlled migration history
  • You need seed data or manual SQL customization

vs. SQL Server Database Projects (SSDT)

FeatureChimpiler ef-migrateSSDT
Schema SourceEF Core modelsHand-written SQL
ToolingCLIVisual Studio
Automation✅ Full⚠️ Limited
Learning CurveLow (if you know EF)Medium-High
Advanced SQL Features⚠️ Limited✅ Full

When to use Chimpiler:

  • Your source of truth is EF Core models
  • You want automation in CI/CD
  • You're building new applications

When to use SSDT:

  • You need advanced SQL Server features
  • Your DBAs prefer SQL-first workflows
  • You have existing database projects

vs. EF Core Power Tools

FeatureChimpiler ef-migrateEF Core Power Tools
ExecutionCLI / AutomatedUI / Manual
OutputDACPACsSQL scripts (via UI)
CI/CD Friendly✅ Yes❌ No
Visual Studio Required❌ No✅ Yes

Supported EF Core Features

✅ Supported:

  • Tables, columns, data types
  • Primary keys (simple and composite)
  • Foreign keys and relationships
  • Indexes (unique and non-unique)
  • Schemas (including custom schemas)
  • Column nullability and max length
  • Identity columns
  • Decimal precision
  • Delete behaviors (Cascade, SetNull, Restrict)
  • Views (simple and indexed views with SCHEMABINDING)
  • View column renames and projections
  • View JOINs across multiple tables

⚠️ Not Yet Supported:

  • Temporal tables
  • Memory-optimized tables
  • Computed columns
  • Check constraints
  • Default constraints
  • Filtered indexes
  • Stored procedures
  • Functions
  • Triggers
  • Full-text indexes
  • Service Broker objects
  • CLR types
  • Row-level security

Working with Views

The ef-migrate tool now supports SQL Server views, including indexed views. To use views, install the Chimpiler.EfMigrate package in your DbContext project:

dotnet add package Chimpiler.EfMigrate

Defining Views

Views are defined using a fluent API in your OnModelCreating method:

using Chimpiler.EfMigrate;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Simple view over a single table
    modelBuilder.Entity<UserSummaryView>(entity =>
    {
        entity.ToView("UserSummaryView")
              .HasViewDefinition<UserSummaryView, MyDbContext>(ctx =>
                  from u in ctx.Users
                  select new UserSummaryView
                  {
                      Id = u.Id,
                      FullName = u.FirstName + " " + u.LastName,
                      Email = u.Email
                  });
        
        entity.HasKey(e => e.Id);
    });

    // Indexed view with SCHEMABINDING
    modelBuilder.Entity<ActiveOrdersView>(entity =>
    {
        entity.ToView("ActiveOrdersView")
              .HasViewDefinition<ActiveOrdersView, MyDbContext>(ctx =>
                  from o in ctx.Orders
                  where o.Status == "Active"
                  select new ActiveOrdersView
                  {
                      OrderId = o.Id,
                      CustomerName = o.CustomerName,
                      TotalAmount = o.TotalAmount
                  })
              .WithSchemaBinding()
              .HasClusteredIndex(v => v.OrderId);
        
        entity.HasKey(e => e.OrderId);
    });

    // View with JOIN
    modelBuilder.Entity<OrderDetailsView>(entity =>
    {
        entity.ToView("OrderDetailsView")
              .HasViewDefinition<OrderDetailsView, MyDbContext>(ctx =>
                  from o in ctx.Orders
                  join c in ctx.Customers on o.CustomerId equals c.Id
                  select new OrderDetailsView
                  {
                      OrderId = o.Id,
                      CustomerName = c.Name,
                      CustomerEmail = c.Email,
                      TotalAmount = o.TotalAmount
                  });
        
        entity.HasKey(e => e.OrderId);
    });
}

View Features

  • LINQ-to-SQL Translation: View definitions use standard LINQ queries that are automatically converted to SQL via EF Core's ToQueryString() method
  • Column Renaming: Map source columns to different names in your view entity
  • Indexed Views: Use .WithSchemaBinding() and .HasClusteredIndex() for SQL Server indexed views
  • JOINs: Views can join multiple tables using standard LINQ join syntax
  • Type Safety: The compiler validates your view definitions and catches errors at build time

Escape Hatch for Complex Views

For views that can't be expressed in LINQ (e.g., CTEs, window functions), use raw SQL:

entity.ToView("ComplexView")
      .HasViewSql(@"
          WITH SalesCTE AS (
              SELECT ProductId, SUM(Quantity) as TotalSales
              FROM OrderItems
              GROUP BY ProductId
          )
          SELECT p.Id, p.Name, COALESCE(s.TotalSales, 0) as TotalSales
          FROM Products p
          LEFT JOIN SalesCTE s ON p.Id = s.ProductId
      ");

Important Notes

  • Views are created after tables in the DACPAC, ensuring proper dependencies
  • EF Core must be able to translate your LINQ query to SQL - complex expressions may not be supported
  • For SCHEMABINDING views, table references are automatically qualified with schema names
  • The first index on an indexed view must be a unique clustered index

These limitations are documented and may be addressed in future releases.

Requirements

  • .NET 10 or later
  • SQL Server DacFx libraries (automatically included via NuGet)
  • Entity Framework Core 10.x (in your target assembly)

Development

Build

dotnet build

Run Tests

dotnet test

All tests are located in tests/Chimpiler.Tests with test fixtures in tests/Chimpiler.TestFixtures.

Run Locally

dotnet run --project src/Chimpiler/Chimpiler.csproj -- ef-migrate --assembly <path> --output <path>

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

MIT License - See LICENSE for details.

Roadmap

Future subcommands and features may include:

  • Additional database providers (PostgreSQL, MySQL)
  • Schema comparison tools
  • Migration generation from model diffs
  • Data seeding utilities
  • And more...

Chimpiler is designed to grow into a comprehensive database tooling ecosystem. The ef-migrate command is just the beginning.


Built with ❤️ using .NET 10

clawcker
dacpac
efcore
ef-migrate
migrations
openclaw

joelmartinez/chimpiler

C#

0

60 commits

updated Aug 29, 2026

See the code

README

Chimpiler

A multi-purpose CLI tooling ecosystem for .NET.

Overview

Chimpiler is an extensible CLI framework designed to provide pragmatic tooling for modern .NET applications and development workflows.

Features

chimpiler clawcker — OpenClaw Instance Manager

Clawcker makes it trivially easy to create, run, and access local OpenClaw instances using Docker. Get started with just three commands:

chimpiler clawcker new myagent
chimpiler clawcker start myagent
chimpiler clawcker talk myagent

Key Features:

  • ✅ One-command instance creation
  • ✅ Automatic Docker image pulling
  • ✅ Secure random token generation
  • ✅ Persistent configuration and workspace
  • ✅ Easy web UI access
  • ✅ Multiple instance management

Learn more about Clawcker →

chimpiler ef-migrate — EF Core Model → DACPAC Generator

The ef-migrate command generates one or more DACPAC files from EF Core DbContext models defined in a compiled .NET assembly. Each DbContext represents a distinct database, and the tool emits one DACPAC per DbContext without requiring:

  • A live database connection
  • Existing EF Core migrations
  • Manual SQL scripting
  • Database import/export workflows

Key Benefits:

  • ✅ Fully automated, CI-friendly workflow
  • ✅ Model-driven schema generation
  • ✅ DACPAC artifacts compatible with SqlPackage and Azure DevOps
  • ✅ Deterministic and repeatable output
  • ✅ No dependency on SQL Server during build

Learn more about ef-migrate →

chimpiler dacpac apply — DACPAC → PostgreSQL Schema Deployment

The dacpac apply command reads SQL Server Database Project DACPACs through public DacFx APIs and translates a deliberately limited, validated subset into PostgreSQL DDL.

export CHIMPILER_DACPAC_CONNECTION_STRING='Host=localhost;Database=app;Username=app;Password=...'
chimpiler dacpac apply ./Database.dacpac --dry-run
chimpiler dacpac apply ./Database.dacpac

Safety and deployment behavior:

  • ✅ Deterministic state-based planning with no rename inference
  • ✅ PostgreSQL catalog introspection, transaction rollback, and advisory locking
  • ✅ Dry-run and reviewable script output
  • ✅ Destructive operations blocked unless --allow-destructive is supplied
  • ✅ Unsupported objects, expressions, and DACPAC deployment scripts rejected before connecting
  • ✅ Provider-neutral library boundary for future MySQL support

This is not SqlPackage for PostgreSQL. Chimpiler independently implements the PostgreSQL planner and executor and uses DacFx only to read the package model through public APIs.

Learn more about dacpac apply →

chimpiler kb — Local GraphRAG Knowledge Base

The kb command builds and queries a completely local, zero-cloud, zero-Python knowledge base stored in a single SQLite file. It is designed for local CLI and agent harness use: agents can retrieve direct evidence, then maintain a focused, evidence-backed graph of entities and relationships using the agent's own reasoning.

chimpiler kb init
chimpiler kb add ./docs
chimpiler kb graph-search "how do I generate a dacpac?"

Key Features:

  • ✅ SQLite is the only database — no server, no Python, no cloud
  • ✅ Local ONNX embedding models, downloaded on first use
  • ✅ Vectors and a lightweight knowledge graph in the same file
  • ✅ Semantic search plus bounded traversal of agent-authored evidence relationships
  • ✅ Agent-ready prompt, entity registration, and evidence-bearing relationship enrichment
  • ✅ Pluggable IEmbeddingProvider for future cloud providers

Learn more about kb →

Give a local agent this prompt

Copy this into a local/CLI agent harness before asking it to use a knowledge base:

Use Chimpiler's local KB as your knowledge-retrieval tool.

If `chimpiler` is not available, install it with:
dotnet tool install --global Chimpiler --add-source https://api.nuget.org/v3/index.json --ignore-failed-sources

Then run:
chimpiler kb prompt

Follow that output. Use `chimpiler kb search` for direct evidence. Delegate distinct source themes
to subagents when useful, returning only cited entity/relationship candidates to the orchestrator.
Register only verified entities and relationships, then use `chimpiler kb graph-search --depth 2`
to follow those focused evidence links. Depth is relationship hops; inspect each returned `trail:`
and cited source before treating a `(graph)` result as evidence.

Installation

As a .NET Global Tool

Install Chimpiler globally using the .NET CLI:

dotnet tool install -g Chimpiler

To update to the latest version:

dotnet tool update -g Chimpiler

If a configured package mirror reports an older version or the installed CLI lacks kb, use NuGet.org explicitly:

dotnet tool update -g Chimpiler --add-source https://api.nuget.org/v3/index.json --ignore-failed-sources
chimpiler kb --help

After installation, run chimpiler kb prompt for concise instructions that can be injected into a local agent's context.

From Source

git clone https://github.com/joelmartinez/chimpiler.git
cd chimpiler
dotnet build
dotnet pack src/Chimpiler/Chimpiler.csproj -c Release
dotnet tool install -g --add-source ./src/Chimpiler/bin/Release Chimpiler

Usage

Basic Usage

Generate DACPACs for all DbContexts in an assembly:

chimpiler ef-migrate --assembly path/to/YourApp.dll

Preview applying a DACPAC to PostgreSQL:

chimpiler dacpac apply path/to/Database.dacpac \
  --provider postgresql \
  --connection-string "$CHIMPILER_DACPAC_CONNECTION_STRING" \
  --dry-run

Write a reviewable script without changing the target:

chimpiler dacpac apply path/to/Database.dacpac --script ./deployment.sql

This will discover all DbContext types in the assembly and generate a DACPAC for each in the ./output directory.

Specify a Single DbContext

Generate a DACPAC for a specific DbContext:

chimpiler ef-migrate --assembly path/to/YourApp.dll --context YourNamespace.OrdersDbContext

Custom Output Directory

chimpiler ef-migrate --assembly path/to/YourApp.dll --output ./dacpacs

Enable Verbose Logging

chimpiler ef-migrate --assembly path/to/YourApp.dll --verbose

Command Reference

dacpac apply

Apply a supported DACPAC schema subset to PostgreSQL.

OptionRequiredDescriptionDefault
<dacpac>✅Path to the DACPAC-
--provider❌Target provider (postgresql; MySQL reserved for future support)postgresql
--connection-string✅*Target connection stringCHIMPILER_DACPAC_CONNECTION_STRING
--dry-run❌Print the plan and roll backfalse
--script <path>❌Write the plan and roll back-
--allow-destructive❌Permit reviewed destructive operationsfalse

* Required through either the option or environment variable.

ef-migrate

Generate DACPACs from EF Core DbContext models.

Options:

OptionAliasRequiredDescriptionDefault
--assembly-a✅Path to compiled .NET assembly containing DbContext types-
--context-c❌Fully qualified type name of a specific DbContextAll DbContexts
--output-o❌Output directory for generated DACPACs./output
--framework-f❌Target framework hint for multi-targeted assemblies-
--verbose-v❌Enable detailed loggingfalse

DACPAC Naming

DACPAC files are named based on the DbContext type name with the following rules:

  1. Strip the Context suffix if present
  2. Strip the DbContext suffix if present
  3. Append .dacpac

Examples:

DbContext TypeDACPAC Filename
TheDatabaseContextTheDatabase.dacpac
OrdersDbContextOrders.dacpac
ReportingContextReporting.dacpac
InventoryContextInventory.dacpac

How It Works

  1. Assembly Loading — The tool loads the target assembly via reflection
  2. DbContext Discovery — Discovers all types inheriting from DbContext
  3. Model Extraction — For each DbContext:
    • Instantiates the context
    • Builds the EF Core runtime model
    • Extracts relational metadata (tables, columns, keys, indexes, schemas)
  4. DACPAC Generation — Translates the EF Core model into SQL Server schema objects using DacFx APIs
  5. File Output — Writes each DACPAC to the output directory

Comparison to Alternatives

vs. EF Core Migrations

FeatureChimpiler ef-migrateEF Core Migrations
ApproachState-based (DACPAC)Migration-based
Output.dacpac filesC# migration files
Database Required❌ No❌ No
DeploymentSqlPackage / Azure DevOpsdotnet ef database update
Change TrackingHandled by SqlPackageHandled by EF Core
ReversibilityVia DACPAC snapshotsVia down migrations

When to use Chimpiler:

  • You prefer state-based deployments
  • You want DACPAC artifacts for CI/CD
  • You're prototyping and need fast iteration

When to use EF Migrations:

  • You need custom migration logic
  • You want version-controlled migration history
  • You need seed data or manual SQL customization

vs. SQL Server Database Projects (SSDT)

FeatureChimpiler ef-migrateSSDT
Schema SourceEF Core modelsHand-written SQL
ToolingCLIVisual Studio
Automation✅ Full⚠️ Limited
Learning CurveLow (if you know EF)Medium-High
Advanced SQL Features⚠️ Limited✅ Full

When to use Chimpiler:

  • Your source of truth is EF Core models
  • You want automation in CI/CD
  • You're building new applications

When to use SSDT:

  • You need advanced SQL Server features
  • Your DBAs prefer SQL-first workflows
  • You have existing database projects

vs. EF Core Power Tools

FeatureChimpiler ef-migrateEF Core Power Tools
ExecutionCLI / AutomatedUI / Manual
OutputDACPACsSQL scripts (via UI)
CI/CD Friendly✅ Yes❌ No
Visual Studio Required❌ No✅ Yes

Supported EF Core Features

✅ Supported:

  • Tables, columns, data types
  • Primary keys (simple and composite)
  • Foreign keys and relationships
  • Indexes (unique and non-unique)
  • Schemas (including custom schemas)
  • Column nullability and max length
  • Identity columns
  • Decimal precision
  • Delete behaviors (Cascade, SetNull, Restrict)
  • Views (simple and indexed views with SCHEMABINDING)
  • View column renames and projections
  • View JOINs across multiple tables

⚠️ Not Yet Supported:

  • Temporal tables
  • Memory-optimized tables
  • Computed columns
  • Check constraints
  • Default constraints
  • Filtered indexes
  • Stored procedures
  • Functions
  • Triggers
  • Full-text indexes
  • Service Broker objects
  • CLR types
  • Row-level security

Working with Views

The ef-migrate tool now supports SQL Server views, including indexed views. To use views, install the Chimpiler.EfMigrate package in your DbContext project:

dotnet add package Chimpiler.EfMigrate

Defining Views

Views are defined using a fluent API in your OnModelCreating method:

using Chimpiler.EfMigrate;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Simple view over a single table
    modelBuilder.Entity<UserSummaryView>(entity =>
    {
        entity.ToView("UserSummaryView")
              .HasViewDefinition<UserSummaryView, MyDbContext>(ctx =>
                  from u in ctx.Users
                  select new UserSummaryView
                  {
                      Id = u.Id,
                      FullName = u.FirstName + " " + u.LastName,
                      Email = u.Email
                  });
        
        entity.HasKey(e => e.Id);
    });

    // Indexed view with SCHEMABINDING
    modelBuilder.Entity<ActiveOrdersView>(entity =>
    {
        entity.ToView("ActiveOrdersView")
              .HasViewDefinition<ActiveOrdersView, MyDbContext>(ctx =>
                  from o in ctx.Orders
                  where o.Status == "Active"
                  select new ActiveOrdersView
                  {
                      OrderId = o.Id,
                      CustomerName = o.CustomerName,
                      TotalAmount = o.TotalAmount
                  })
              .WithSchemaBinding()
              .HasClusteredIndex(v => v.OrderId);
        
        entity.HasKey(e => e.OrderId);
    });

    // View with JOIN
    modelBuilder.Entity<OrderDetailsView>(entity =>
    {
        entity.ToView("OrderDetailsView")
              .HasViewDefinition<OrderDetailsView, MyDbContext>(ctx =>
                  from o in ctx.Orders
                  join c in ctx.Customers on o.CustomerId equals c.Id
                  select new OrderDetailsView
                  {
                      OrderId = o.Id,
                      CustomerName = c.Name,
                      CustomerEmail = c.Email,
                      TotalAmount = o.TotalAmount
                  });
        
        entity.HasKey(e => e.OrderId);
    });
}

View Features

  • LINQ-to-SQL Translation: View definitions use standard LINQ queries that are automatically converted to SQL via EF Core's ToQueryString() method
  • Column Renaming: Map source columns to different names in your view entity
  • Indexed Views: Use .WithSchemaBinding() and .HasClusteredIndex() for SQL Server indexed views
  • JOINs: Views can join multiple tables using standard LINQ join syntax
  • Type Safety: The compiler validates your view definitions and catches errors at build time

Escape Hatch for Complex Views

For views that can't be expressed in LINQ (e.g., CTEs, window functions), use raw SQL:

entity.ToView("ComplexView")
      .HasViewSql(@"
          WITH SalesCTE AS (
              SELECT ProductId, SUM(Quantity) as TotalSales
              FROM OrderItems
              GROUP BY ProductId
          )
          SELECT p.Id, p.Name, COALESCE(s.TotalSales, 0) as TotalSales
          FROM Products p
          LEFT JOIN SalesCTE s ON p.Id = s.ProductId
      ");

Important Notes

  • Views are created after tables in the DACPAC, ensuring proper dependencies
  • EF Core must be able to translate your LINQ query to SQL - complex expressions may not be supported
  • For SCHEMABINDING views, table references are automatically qualified with schema names
  • The first index on an indexed view must be a unique clustered index

These limitations are documented and may be addressed in future releases.

Requirements

  • .NET 10 or later
  • SQL Server DacFx libraries (automatically included via NuGet)
  • Entity Framework Core 10.x (in your target assembly)

Development

Build

dotnet build

Run Tests

dotnet test

All tests are located in tests/Chimpiler.Tests with test fixtures in tests/Chimpiler.TestFixtures.

Run Locally

dotnet run --project src/Chimpiler/Chimpiler.csproj -- ef-migrate --assembly <path> --output <path>

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

MIT License - See LICENSE for details.

Roadmap

Future subcommands and features may include:

  • Additional database providers (PostgreSQL, MySQL)
  • Schema comparison tools
  • Migration generation from model diffs
  • Data seeding utilities
  • And more...

Chimpiler is designed to grow into a comprehensive database tooling ecosystem. The ef-migrate command is just the beginning.


Built with ❤️ using .NET 10

clawcker
dacpac
efcore
ef-migrate
migrations
openclaw