LowCodeHub.QueryableExtensions 0.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package LowCodeHub.QueryableExtensions --version 0.0.2
                    
NuGet\Install-Package LowCodeHub.QueryableExtensions -Version 0.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LowCodeHub.QueryableExtensions" Version="0.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.QueryableExtensions" Version="0.0.2" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.QueryableExtensions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LowCodeHub.QueryableExtensions --version 0.0.2
                    
#r "nuget: LowCodeHub.QueryableExtensions, 0.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LowCodeHub.QueryableExtensions@0.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LowCodeHub.QueryableExtensions&version=0.0.2
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.QueryableExtensions&version=0.0.2
                    
Install as a Cake Tool

LowCodeHub.QueryableExtensions

Reusable query and EF Core building blocks for ASP.NET Core — LINQ filtering, dynamic ordering, pagination, specification pattern, lookup tables with localization, enum-to-lookup mapping, and transactional execution with retry support.

NuGet License: MIT

Why This Library?

Feature LowCodeHub.QueryableExtensions Manual EF Core Other Query Libraries
Pagination ToPagedListAsync() — one call Manual Skip/Take Varies
Dynamic ordering OrderByColumn("name") from string Switch statements Expression builders
Multi-column search MultiColumnSearchLike() — EF-translated Manual Contains per column Full-text search
Specification pattern Built-in — filter, project, update, add (single + range), scalar (sync + async) Manual Ardalis.Specification
Lookup tables First-class — localized, enum-mapped Manual entity + queries Manual
Transactions Manager + retry with isolation level control Manual BeginTransaction Manual
Base entities BaseEntity<T> + tracked + soft-deletable variants Manual Manual
Localized values Localized dictionary with language fallback Manual Manual
Audit triggers Provider-agnostic — DbContext or DbConnection overloads Manual triggers Manual
JSON functions EF-translated JSON_VALUE + JSON_QUERY (SQL Server, Oracle, MySQL) Raw SQL Manual

Installation

dotnet add package LowCodeHub.QueryableExtensions

Quick Start

// Pagination
var paged = await dbContext.Users
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .ToPagedListAsync(page: 1, pageSize: 20, ct);

// Dynamic ordering from query string
var ordered = dbContext.Orders
    .OrderByColumn("createdDate")
    .ToPagedListAsync(page, pageSize, ct);

// Specification pattern
var activeUsers = await dbContext.Users
    .WithSpecification(new ActiveUsersSpecification())
    .ToListAsync(ct);

// Transaction with retry
await transactionManager.ExecuteInTransactionWithRetryAsync(async scope =>
{
    // data changes — auto-commit on success, auto-rollback on failure
}, IsolationLevel.ReadCommitted, ct);

Table of Contents


Pagination

Basic Pagination

PagedList<User> result = await dbContext.Users
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .ToPagedListAsync(page: 1, pageSize: 20, ct);

// result.Items         — List<User>
// result.Page          — 1
// result.PageSize      — 20
// result.TotalCount    — 150
// result.TotalPages    — 8
// result.HasNextPage   — true
// result.HasPreviousPage — false

From a PagedQueryBase Request

public record GetUsersRequest : PagedQueryBase;

PagedList<User> result = await dbContext.Users
    .ToPagedListAsync(request, ct);

PagedQueryBase includes: PageNumber, PageSize, Filter, SortColumn, SortOrder, Language.

Attached Paged List

Attach additional data to the paged result:

AttachedPagedList<Order, OrderSummary> result = await dbContext.Orders
    .ToAttachedPagedListAsync(page, pageSize, summary, ct);

Filtering

Multi-Column Search (LIKE)

Search across multiple string columns with a single query — translated to SQL LIKE:

var results = await dbContext.Users
    .MultiColumnSearchLike(searchTerm, u => u.Name, u => u.Email, u => u.Phone)
    .ToListAsync(ct);

GroupBy with Count

var grouped = await dbContext.Orders
    .GroupByWithCountAsync(o => o.Status, ct);
// Dictionary<OrderStatus, int>

Dynamic Ordering

Order by column name as a string — useful for API endpoints with sort parameters:

var ordered = dbContext.Users
    .OrderByColumn("name")                    // ascending
    .ThenByColumnDescending("createdDate");   // descending

// With sort order enum
var ordered = dbContext.Users
    .TryOrderByColumn("name", SortOrder.Descending);

// Mapped key ordering (map API names to entity properties)
var ordered = dbContext.Users
    .OrderByMappedKey("displayName", new Dictionary<string, Expression<Func<User, object>>>
    {
        ["displayName"] = u => u.Name,
        ["created"] = u => u.CreatedDate
    });

Specification Pattern

Filter Specifications

public sealed class ActiveUsersSpecification : ISpecification<User>
{
    public IQueryable<User> Where(IQueryable<User> query)
        => query.Where(u => u.IsActive && !u.IsDeleted);
}

var users = await dbContext.Users
    .WithSpecification(new ActiveUsersSpecification())
    .ToListAsync(ct);

Projection Specifications

public sealed class UserSummarySpecification : ISpecification<User, UserSummaryDto>
{
    public IQueryable<UserSummaryDto> Select(IQueryable<User> query)
        => query.Select(u => new UserSummaryDto(u.Id, u.Name, u.Email));
}

var summaries = await dbContext.Users
    .WithSpecification(new ActiveUsersSpecification(), new UserSummarySpecification())
    .ToListAsync(ct);

Update Specifications

public sealed class DeactivateUserSpecification : IUpdateSpecification<User>
{
    public Action<UpdateSettersBuilder<User>> Update()
        => setters => setters.SetProperty(u => u.IsActive, false);
}

await dbContext.Users
    .Where(u => u.LastLoginAt < cutoff)
    .UpdateWithSpecificationAsync(new DeactivateUserSpecification(), ct);

Add Specifications

Add a single entity:

public sealed class NewUserSpecification : IAddSpecification<User>
{
    public User Add() => new User { Name = "John", IsActive = true };
}

await dbContext.Set<User>().AddWithSpecification(new NewUserSpecification());

Add multiple entities with IAddRangeSpecification<T>:

public sealed class SeedRolesSpecification : IAddRangeSpecification<Role>
{
    public IEnumerable<Role> AddRange()
        => new[]
        {
            new Role { Name = "Admin" },
            new Role { Name = "Editor" },
            new Role { Name = "Viewer" }
        };
}

await dbContext.Set<Role>().AddRangeWithSpecification(new SeedRolesSpecification());

Scalar Specifications

Async scalar:

public sealed class UserCountSpecification : IScalarSpecificationAsync<User, int>
{
    public Task<int> ExecuteAsync(IQueryable<User> query, CancellationToken ct)
        => query.CountAsync(ct);
}

int count = await dbContext.Users
    .ExecuteScalarSpecificationAsync(new UserCountSpecification(), ct);

Sync scalar:

public sealed class HasActiveUsersSpecification : IScalarSpecification<User, bool>
{
    public bool Execute(IQueryable<User> query)
        => query.Any(u => u.IsActive);
}

bool hasActive = dbContext.Users
    .ExecuteScalarSpecification(new HasActiveUsersSpecification());

Lookup Tables

Lookup Entities

The library provides LookupSetEntity and LookupItemEntity for managing lookup/reference data:

// Register in DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.AddLookupSupport();
    base.OnModelCreating(modelBuilder);
}

// Register DI services
builder.Services.AddLookupSupport<MyDbContext>();

Lookup Repository

// Get all options for a lookup set
var options = await lookupRepository.GetOptionsAsync(
    "ORDER_STATUS", "en", cancellationToken: ct);

// Queryable API
var options = (await dbContext.Set<LookupItemEntity>()
    .WhereActive()
    .WhereSetCode("ORDER_STATUS")
    .OrderBySortOrder()
    .ToListAsync(ct))
    .ToLookupOptions("en");

Enum-to-Lookup Mapping

Map enum values to lookup codes:

public enum OrderStatus
{
    [LookupCode("PENDING")]
    Pending,

    [LookupCode("APPROVED")]
    Approved,

    [LookupCode("SHIPPED")]
    Shipped
}

// Enum → code
string code = OrderStatus.Pending.ToCode();     // "PENDING"

// Code → enum
OrderStatus status = "APPROVED".ToEnum<OrderStatus>(); // OrderStatus.Approved

Localized Values

The Localized type is a dictionary-based value object for multilingual text:

var name = new Localized(new Dictionary<string, string>
{
    ["en"] = "Active",
    ["ar"] = "نشط"
});

// Get with language fallback
string value = name.TryGetLocal("ar");  // "نشط"
string value = name.TryGetLocal("fr");  // falls back to first available

Use GetValue extension for language-aware lookup with fallback:

string value = dictionary.GetValue("ar"); // returns Arabic if available, else first value

Transaction Manager

Basic Transaction

builder.Services.AddTransactionManager<MyDbContext>();
await transactionManager.ExecuteInTransactionAsync(async scope =>
{
    // data changes
    // auto-commit on success, auto-rollback on failure
}, ct);

With Isolation Level

await transactionManager.ExecuteInTransactionAsync(async scope =>
{
    // data changes
}, IsolationLevel.ReadCommitted, ct);

With Retry (for transient failures)

await transactionManager.ExecuteInTransactionWithRetryAsync(async scope =>
{
    // data changes — retried on transient failures
}, IsolationLevel.ReadCommitted, ct);

With Return Value

var result = await transactionManager.ExecuteInTransactionAsync(async scope =>
{
    var order = await CreateOrderAsync();
    return order.Id;
}, ct);

Manual commit/rollback is still supported via scope.CommitAsync() / scope.RollbackAsync().


Base Entities

BaseEntity

public class Order : BaseEntity<Guid>
{
    // Inherits: Id (Guid)
    public string Name { get; set; }
}

TrackedBaseEntity

public class Order : TrackedBaseEntity<Guid>
{
    // Inherits: Id, CreatedBy, ModifiedBy, CreatedDate, UpdatedDate
    public string Name { get; set; }
}

SoftDeletableEntity

For entities that support soft deletion (logical delete without removing the row):

public class Order : SoftDeletableEntity<Guid>
{
    // Inherits: Id, CreatedBy, ModifiedBy, CreatedDate, UpdatedDate, IsDeleted
    public string Name { get; set; }
}

IsDeleted is bool? — null means not deleted, true means soft-deleted.


Audit Triggers

Provider-agnostic database audit triggers that automatically record every INSERT, UPDATE, and DELETE into a shared AuditTrail table, capturing old and new values as JSON. Works with any EF Core provider — SQL Server, PostgreSQL, MySQL, SQLite, etc.

Pass your DbContext directly — the connection is obtained from it and managed internally. No manual open/close required:

await dbContext.EnableAuditTriggersAsync(
    provider: new SqlServerAuditTriggerProvider(),  // or PostgreSqlAuditTriggerProvider, etc.
    tables:
    [
        new AuditedTable("Orders"),
        new AuditedTable("OrderItems", schema: "sales")
    ],
    auditTableSchema: "dbo",
    cancellationToken: ct);

Sync version:

dbContext.EnableAuditTriggers(
    provider: new SqlServerAuditTriggerProvider(),
    tables:
    [
        new AuditedTable("Orders"),
        new AuditedTable("Payments")
    ],
    auditTableSchema: "dbo");

Typically called once at application startup, after migrations:

var app = builder.Build();

await app.RunDatabaseMigrationAsync<Program>(); // if using LowCodeHub.Migration.SqlServer

using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.EnableAuditTriggersAsync(
    provider: new SqlServerAuditTriggerProvider(),
    tables: [new AuditedTable("Orders"), new AuditedTable("Users")]);

app.Run();

Setup via DbConnection (manual lifecycle)

If you manage the connection yourself, use the DbConnection overloads. The connection must already be open:

using var connection = new SqlConnection(connectionString);
connection.Open();

connection.EnableAuditTriggers(
    provider: new SqlServerAuditTriggerProvider(),
    tables: [new AuditedTable("Orders")],
    auditTableSchema: "dbo");

What It Does

  1. Creates the AuditTrail table (if not exists) in the specified schema.
  2. For each specified table, discovers its columns.
  3. Installs INSERT, UPDATE, and DELETE triggers that write to AuditTrail with old/new values as JSON.

AuditedTable

new AuditedTable(name: "Orders")              // uses default schema
new AuditedTable(name: "Orders", schema: "sales")  // explicit schema

IAuditTriggerSqlProvider

Supply a provider for your target database. Implement this interface to support additional databases:

public interface IAuditTriggerSqlProvider
{
    IEnumerable<string> GenerateCreateAuditTableStatements(string auditSchema);
    IEnumerable<string> GenerateCreateAuditTriggerStatements(
        string tableName, string? schema, string auditSchema, List<string> columns);
    string GenerateGetColumnsQuery(string tableName, string? schema);
}

JSON Functions

EF Core-translated mappings for JSON path functions. Register once on your ModelBuilder, then use them freely in LINQ queries — EF Core emits the corresponding SQL function call.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.AddJsonFunctions();
    base.OnModelCreating(modelBuilder);
}
Method SQL Function Supported Providers Description
JsonValue(source, path) JSON_VALUE SQL Server 2016+, Oracle 12.2+, MySQL 8.0.21+ Returns a scalar string from a JSON path
JsonQuery(source, path) JSON_QUERY SQL Server 2016+, Oracle 12.2+ Returns a JSON object or array at a path

ISJSON and JSON_PATH_EXISTS were intentionally excluded — they are SQL Server-only functions with no equivalent in other providers.

Example:

// Filter orders by a JSON property stored in a NVARCHAR/VARCHAR column
var europeOrders = await dbContext.Orders
    .Where(o => JsonExtensions.JsonValue(o.MetadataJson, "$.region") == "eu")
    .ToListAsync(ct);

// Extract a nested JSON object
var addresses = await dbContext.Customers
    .Select(c => JsonExtensions.JsonQuery(c.ProfileJson, "$.address"))
    .ToListAsync(ct);

These methods are not executed in .NET — they translate to SQL. Calling them outside a LINQ-to-SQL query throws NotSupportedException.


How It Works

┌─────────────────────────────────────────────────────────┐
│  Your IQueryable<T> pipeline                            │
│                                                         │
│  dbContext.Users                                        │
│    .WithSpecification(new ActiveUsersSpec())             │
│    .MultiColumnSearchLike("john", u => u.Name, ...)    │
│    .OrderByColumn("name")                               │
│    .ToPagedListAsync(1, 20, ct)                         │
│                                                         │
│  → Translated to single SQL query by EF Core            │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│  Transaction Manager                                    │
│                                                         │
│  ExecuteInTransactionWithRetryAsync(scope => {          │
│    // BEGIN TRAN (isolation level)                       │
│    // ... your data changes ...                         │
│    // COMMIT on success / ROLLBACK on failure           │
│    // Auto-retry on transient failures                  │
│  })                                                     │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│  Lookup System                                          │
│                                                         │
│  LookupSetEntity (1) ──→ (*) LookupItemEntity           │
│       │                        │                        │
│  "ORDER_STATUS"            Code: "PENDING"              │
│                            Name: {"en":"Pending",...}    │
│                            SortOrder: 1                 │
│                            IsActive: true               │
│                                                         │
│  Enum ←→ LookupCode mapping via [LookupCode] attribute │
└─────────────────────────────────────────────────────────┘

Requirements

  • .NET 10 or later
  • Microsoft.EntityFrameworkCore.Relational 10.0+ (included as a dependency)

License

MIT © Ahmed Abuelnour

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 111 11/15/2026
0.0.13 123 10/22/2026
0.0.12 181 8/6/2026
0.0.11 263 6/23/2026
0.0.10 141 6/21/2026
0.0.6 167 5/19/2026
0.0.5 134 5/18/2026
0.0.3 143 5/12/2026
0.0.2 191 4/23/2026
0.0.1 3,196 3/26/2026