Dapper.FastCrud Documentation
repository·master·Indexed 19 days ago
https://github.com/moonstorm/fastcrudA high-performance, type-safe ORM built on top of Dapper that bridges the gap between raw SQL speed and structured ORM maintainability. It supports multiple databases including MS SQL Server, MySQL, SQLite, PostgreSQL, and SAP/Sybase SQL Anywhere. Key features include a fluent statement builder via Find<T>, support for composite primary keys, and a database-first entity generator via the Dapper.FastCrud.ModelGenerator NuGet package.
What's inside Dapper.FastCrud
- Dapper.FastCrud is a fast ORM designed to provide type safety and clean code while maintaining performance close to raw SQL. It leverages C# 6 / VB 14 features to reduce errors caused by mistypings or database entity refactorings. It is intended for use in the Data Access Layer (DAL) where developers want the speed of Dapper but with more structured, type-safe query construction.
Understand the StatementOptions hierarchy
masterDapper.FastCrud uses a layered approach to manage query options. Understanding this hierarchy helps you know which interfaces to use for configuring your SQL statements:
- Aggregated Options: These are the final, internal options used by the core algorithms.
AggregatedSqlStatementOptionscontains the primary query options, whileAggregatedRelationalSqlStatementOptionsstores options related to JOINed entities. - Situational Options: These are public interfaces that expose only a subset of the total available options, tailored to specific statement types. For example:
IStandardSqlStatementOptionsSetter: Methods available for all statement types.IRangedConditionalSqlStatementOptionsSetter: Methods available only when a statement is expected to return a range of entities.
- Situational Builders: These are the public fluent interfaces you interact with. They combine multiple situational option setters into a single builder and use an internal implementation to map your calls directly onto the underlying aggregated options builder.
- Aggregated Options: These are the final, internal options used by the core algorithms.
Key Features of Dapper.FastCrud
masterCore Capabilities
- Composite Keys: Supports entities with composite primary keys (note: CRUD operations require UNIQUE primary keys).
- Multiple Entity Mappings: Supports partial queries for large denormalized tables and data migrations.
- Transaction & Timeout Support: All CRUD methods accept a transaction, a command timeout, and a custom entity mapping.
- Relationships: Supports opt-in relationships. As of version 3.0, self-referenced entities and multiple joins to the same target are supported via aliases.
- Formattables: Includes a set of "formattables" for use in query construction even if you don't use the full CRUD features.
Tooling
- Model Generator: A generic T4 template for C# is provided via the
Dapper.FastCrud.ModelGeneratorNuGet package.
Core Features and Capabilities
masterDapper.FastCrud provides several advanced features for database interaction:
- Composite Primary Keys: Supported for entities, but note that standard CRUD operations require UNIQUE primary keys.
- Multiple Entity Mappings: Useful for partial queries in large denormalized tables or data migrations.
- Transaction and Timeout Support: All CRUD methods accept a transaction, a command timeout, and a custom entity mapping.
- Opt-in Relationships: Supports self-referenced entities, one-to-one relationships, and multiple joins to the same target via aliases.
- Flexible Joins: JOIN support is extended to
GETandCOUNTmethods. You can join with any navigation property (or none) and anyONclause without requiring a pre-set relationship in the mappings. - SQL Formattables: A set of formatters available via the
Sqlstatic class to resolve raw names and SQL-ready counterparts.
Generate entities using Dapper.FastCrud.ModelGenerator
masterYou can perform entity generation using a database-first approach (currently limited to SQL Server) by following these steps:
- Install the NuGet package
Dapper.FastCrud.ModelGenerator. - Create your own T4 template files (ending in
*Config.tt) using the generic template provided within the package.
For more detailed implementation instructions, refer to the wiki section on the project website.
dotnet add package Dapper.FastCrud.ModelGenerator- Install the NuGet package
Install Dapper.FastCrud and Model Generator
masterInstall the main library and the model generator via NuGet to start using the ORM and the T4 template generator.
# Install the main library dotnet add package Dapper.FastCrud # Install the model generator dotnet add package Dapper.FastCrud.ModelGeneratorPerform complex queries with Find<T>
masterYou can use the
Find<T>method on adbConnectionto build type-safe queries using a fluent statement builder. This allows for aliasing, joining multiple entities, filtering withWhere, ordering, and pagination (Skip/Top).To ensure type safety when referencing properties and aliases, use the following format specifiers:
{nameof(Property):of alias}: Resolves the property name relative to a specific table alias.{nameof(Property):P}: Formats the property name as a SQL parameter.
Example of a complex query with an inner join and aliasing:
var queryParams = new { FirstName = "John", Street = "Creek Street" }; var persons = dbConnection.Find<Person>(statement => statement .WithAlias("person") .Include<Address>(join => join .InnerJoin() .WithAlias("address")) .Where($@" {nameof(Person.FirstName):of person} = {nameof(queryParams.FirstName):P} AND {nameof(Address.Street):of address} = {nameof(queryParams.Street):P}") .OrderBy($"{nameof(Person.LastName):of person} DESC") .Skip(10) .Top(20) .WithParameters(queryParams);Example of generated entity output
masterThe
Dapper.FastCrud.ModelGeneratorproduces partial classes decorated with attributes for mapping to database tables and columns. It handles primary keys, foreign keys, and navigation properties for relationships./// <summary> /// Represents the 'Badges' table. /// </summary> [Table("Badges")] public partial class BadgeEntity { /// <summary> /// Represents the column 'Id'. /// </summary> [Key] [Column(Order = 1)] [ForeignKey(nameof(Employee))] public virtual int AssetId { get; set; } /// <summary> /// Represents the column 'EmployeeId'. /// </summary> [Key] [Column(Order = 2)] [ForeignKey(nameof(Employee))] public virtual Guid EmployeeId { get; set; } /// <summary> /// Represents the column 'Barcode'. /// </summary> public virtual string Barcode { get; set; } /// <summary> /// Represents the navigation property for the child-parent relationship involving <seealso cref="EmployeeEntity"/> /// </summary> public virtual EmployeeEntity? Employee { get; set; } }Perform type-safe queries with Find<T>
masterYou can use the
Find<T>method on adbConnectionto build complex, type-safe queries using a fluent statement builder. This allows for aliasing, including related entities via joins, filtering with type-safe property names, ordering, skipping, and taking a specific number of records.To ensure type safety in the
Whereclause, use the custom "formattables" like:of(to get the column name with an alias) and:P(to get a parameter placeholder).// Create parameters for the query var queryParams = new { FirstName = "John", Street = "Creek Street" }; // Get persons using the above created query parameters var persons = dbConnection.Find<Person>(statement => statement .WithAlias("person") .Include<Address>(join => join.InnerJoin() .WithAlias("address")) .Where($@" {nameof(Person.FirstName):of person} = {nameof(queryParams.FirstName):P} AND {nameof(Address.Street):of address} = {nameof(queryParams.Street):P}") .OrderBy($"{nameof(Person.LastName):of person} DESC") .Skip(10) .Top(20) .WithParameters(queryParams);Release notes for Dapper.FastCrud.ModelGenerator 3.0
masterMajor updates and breaking changes in version 3.0 include:
- Breaking Changes:
- Support for composite primary keys.
- Support for self-referenced entities.
- Support for multiple references to the same target using the
InversePropertyattribute.
- Improvements:
- Better handling of columns representing C# reserved keywords.
- Support for new
csprojstyle projects. - Fixed compatibility issues with VS2019 and later.
- Breaking Changes:
Release notes for Dapper.FastCrud.ModelGenerator 3.3
masterRecent updates in version 3.3 include:
- Schema Support: Added an opt-in flag for generating schema-decorated entities and fixed issues with identical table names in separate schemas and metadata extraction.
- Nullability: Parent entity properties are now generated as nullable. Added warning suppressions for non-nullable properties.
- New Types: Added support for
TimeOnlyandDateOnly. - Customization: Added support for customizable entity class modifiers and entity property modifiers.
Supported Databases and Mapping Styles
masterSupported Databases
- LocalDb
- MS SQL Server
- MySQL
- SQLite
- PostgreSQL
- SAP/Sybase SQL Anywhere
Supported Mapping Styles
- Code first: Using model data annotations (preferred).
- Fluent registration: For POCO objects.
- Semi-POCO: Using metadata objects.
- Database first: Limited to SQL Server.