Dapper.FastCrud Documentation

repository·master·Indexed 19 days ago

https://github.com/moonstorm/fastcrud

A 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.

Tokens
2.8K
Snippets
5
Records
12
Agent score
67%

What's inside Dapper.FastCrud

  1. Overview of Dapper.FastCrud

    master
    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.
  2. Understand the StatementOptions hierarchy

    master

    Dapper.FastCrud uses a layered approach to manage query options. Understanding this hierarchy helps you know which interfaces to use for configuring your SQL statements:

    1. Aggregated Options: These are the final, internal options used by the core algorithms. AggregatedSqlStatementOptions contains the primary query options, while AggregatedRelationalSqlStatementOptions stores options related to JOINed entities.
    2. 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.
    3. 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.
  3. Key Features of Dapper.FastCrud

    master

    Core 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.ModelGenerator NuGet package.
  4. Core Features and Capabilities

    master

    Dapper.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 GET and COUNT methods. You can join with any navigation property (or none) and any ON clause without requiring a pre-set relationship in the mappings.
    • SQL Formattables: A set of formatters available via the Sql static class to resolve raw names and SQL-ready counterparts.
  5. Generate entities using Dapper.FastCrud.ModelGenerator

    master

    You can perform entity generation using a database-first approach (currently limited to SQL Server) by following these steps:

    1. Install the NuGet package Dapper.FastCrud.ModelGenerator.
    2. 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
  6. Install Dapper.FastCrud and Model Generator

    master

    Install 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.ModelGenerator
  7. Perform complex queries with Find<T>

    master

    You can use the Find<T> method on a dbConnection to build type-safe queries using a fluent statement builder. This allows for aliasing, joining multiple entities, filtering with Where, 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);
  8. Example of generated entity output

    master

    The Dapper.FastCrud.ModelGenerator produces 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; }
        }
  9. Perform type-safe queries with Find<T>

    master

    You can use the Find<T> method on a dbConnection to 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 Where clause, 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);
  10. Release notes for Dapper.FastCrud.ModelGenerator 3.0

    master

    Major 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 InverseProperty attribute.
    • Improvements:
      • Better handling of columns representing C# reserved keywords.
      • Support for new csproj style projects.
      • Fixed compatibility issues with VS2019 and later.
  11. Release notes for Dapper.FastCrud.ModelGenerator 3.3

    master

    Recent 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 TimeOnly and DateOnly.
    • Customization: Added support for customizable entity class modifiers and entity property modifiers.
  12. Supported Databases and Mapping Styles

    master

    Supported 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.