I was looking into Google’s Common Expression Language (CEL) recently for a Rust-based project at work, and out of curiosity I checked what the .NET ecosystem had for it. There isn’t much.

The standout is Celly, and credit to bsidio for building a fast, low-allocation CEL primitive for .NET. The parser, type-checker, and interpreter are solid. What seemed missing was a good story for working directly against System.Text.Json and JSON document stores, which is where CEL expressions usually end up in practice.

That pulled me back into a problem that keeps coming up on my teams. Back in 2018 I wrote about Collate.NET, which started as a way to translate Telerik DataGrid requests into Entity Framework queries without writing endless switch (request.FilterField) blocks or adopting all of OData. A couple years later I wrote EFQueryScript to keep raw SQL out of C# string literals. Both are long since decommissioned. EF Core’s SQL APIs caught up with EFQueryScript, and Collate.NET’s PageAndFilterAndSortRequest DTO ran out of steam as soon as you needed boolean logic, nested properties, or collection predicates.

The underlying problem hasn’t changed, though: how do you give a front-end a flexible query language without leaking your data model and back-end internals, the way full OData tends to? We ran into it again recently on an Azure AI Search-backed UI. We didn’t want the front-end to know anything about Azure Search syntax or backing index field names. We wanted a thin translation layer that accepted a terser, controllable subset of filtering and sorting and mapped it onto whatever sat behind the API.

So I built Celly.Json, a three-package suite on NuGet (Celly.Json, Celly.Json.AspNetCore, and Celly.Json.Query). Between lazy JSON evaluation, EF Core LINQ translation, and direct SQL/document query generation, it’s the closest I’ve gotten to what I was actually aiming for with Collate.NET and EFQueryScript.

Why CEL?

CEL sits in the middle ground where most business rules, policy checks, and API filters live:

user.age >= 18 && 'admin' in user.roles && items.exists(i, i.price >= 50 && i.qty > 0)

What makes it safe for untrusted input is what it can’t do. It isn’t Turing-complete, so there are no unbounded loops, no arbitrary method calls, and no way for an expression to hang a thread or touch the filesystem. It parses to a clean AST, type-checks before it runs, and is already used in Kubernetes admission policies, Firebase security rules, and Google AIP-160 API filtering.

Evaluating JSON Without Turning It Into Dictionaries

Most expression evaluators in .NET expect you to deserialize JSON into nested Dictionary<string, object?> and List<object?> trees before they can touch it. That’s fine in a demo, and less fine on a hot path or over a stream of events.

Celly.Json evaluates directly over JsonElement, JsonDocument, and JsonNode lazily. In tight loops you can reuse a single JsonElementActivation with .Reset(...), or stream NDJSON through FilterJsonLines.

using System.Text.Json;
using Celly;
using Celly.Json;

CelProgram program = CelEnv.Default.Compile("user.age >= 18 && 'admin' in user.roles");

using JsonDocument doc = JsonDocument.Parse("""
    { "user": { "age": 32, "roles": ["viewer", "admin"] } }
    """);

bool allowed = program.EvalJsonBool(doc); // true

It also compiles Draft-07 and Draft 2020-12 JSON Schemas into Celly static type declarations, so bad field names or type mismatches fail at check time instead of silently returning false. On .NET 10, JsonSchemaEnv.Create<T>() derives that schema straight from your C# DTOs via JsonSchemaExporter, with JsonTypeInfo<T> overloads for [JsonSerializable] NativeAOT contexts. Schema bounds (maxLength, maxItems, maxProperties) also feed into Celly’s static cost estimator.

Closing the Loop on Collate.NET and EFQueryScript

In-memory evaluation covers webhooks, feature flags, and auth rules. Pushing the same expression down to the database is the more interesting part.

Celly.Json.Query translates a CEL AST into database queries with zero driver or ORM dependencies in the package. For EF Core (including OwnsOne(...).ToJson() columns) or any IQueryable<T>, CelLinqExpressionTranslator builds strongly-typed Expression<Func<T, bool>> trees and AIP-160 style sorting via .WhereCel(...), .OrderByCel(...), and .ThenByCel(...):

using Celly.Json.Query;

var orders = await dbContext.Orders
    .WhereCel("status in ['Shipped', 'Delivered'] && createdAt >= '2026-01-01T00:00:00Z' && items.exists(i, i.price >= 50)")
    .OrderByCel("total desc, user.age asc")
    .ToListAsync();

Property binding checks [JsonPropertyName] first and falls back to case-insensitive CLR property names. Scalar literals are coerced to the property’s CLR type (int, decimal, Enum by name or number, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, and nullable variants) so EF Core emits normal, index-friendly SQL.

If you’re querying JSON documents directly without EF Core, CelSqlQueryTranslator emits parameterized WHERE and ORDER BY clauses for Azure Cosmos DB, PostgreSQL jsonb, SQL Server JSON columns, and SQLite:

CelSqlQuery query = CelSqlQueryTranslator.Translate(
    "tier in ['pro', 'enterprise'] && user.age >= 18",
    CelQueryDialects.PostgresJsonb,
    rootSource: "doc");

// WHERE (((doc #>> '{"tier"}') = ANY(@p0)) AND (((doc #>> '{"user","age"}')::bigint) >= @p1))
// Parameters: @p0 = string[] { "pro", "enterprise" }, @p1 = 18L

Every literal is parameterized, and on PostgreSQL homogeneous in [...] lists collapse into a single typed array parameter (= ANY(@p0)) for better plan caching. MongoFilterTranslator does the same for MongoDB Extended JSON filters. To keep the dialects honest, the integration test suite runs the same CEL expressions against real PostgreSQL 17, SQL Server 2022, MongoDB 8, and Cosmos DB Emulator containers and checks that each one returns the exact same document IDs as an in-memory Celly oracle.

ASP.NET Core Integration

Celly.Json.AspNetCore hooks into ASP.NET Core with a lazy HttpContextActivation (claims, headers, route values, and query params), AddCelPolicy(...) authorization policies, Minimal API .RequireCel(...) endpoint filters, a bounded ICelProgramCache, and Results.Extensions.CelJson(CelValue) to write CEL results straight to Utf8JsonWriter.

app.MapGet("/admin/reports", () => Results.Ok())
    .RequireCel("user.authenticated && 'admin' in user.roles && headers['x-tenant-id'] == route.tenantId");

Packaging and Ground Rules

I kept the dependency graph flat: Celly.Json depends only on Celly and the BCL, Celly.Json.AspNetCore adds only Microsoft.AspNetCore.App, and Celly.Json.Query depends only on Celly.Json. EF Core and database drivers stay in the test projects. Everything multi-targets net10.0 and net11.0 (with Runtime Async on .NET 11), runs with NativeAOT and trim analyzers enabled (with reflection-based overloads and CelLinqExpressionTranslator explicitly marked [RequiresUnreferencedCode] / [RequiresDynamicCode]), and enforces a 90% per-package line coverage floor in CI.

Try It Out

v1.2.0 is on NuGet:

dotnet add package Celly.Json
dotnet add package Celly.Json.AspNetCore
dotnet add package Celly.Json.Query

The code, benchmarks, and docs are at github.com/bradwestness/Celly.Json and on the Wiki.

The Road Ahead

v1.2.0 covers the core evaluation, ASP.NET Core, and query-translation surface, but there is still plenty left on the roadmap. Near term, I’m focused on query safety guardrails for untrusted API filters (field allowlists and denylists, max AST depth, list-size and comprehension nesting limits), opt-in caching for translated LINQ expressions and SQL templates, and zero-dependency Meter and ActivitySource instrumentation for ASP.NET Core.

After that, I want to add PostgreSQL jsonb GIN index (@>) support so equality and array-containment predicates can hit jsonb_path_ops indexes, Minimal API query binders (CelFilter<T> / CelOrderBy<T>) with automatic ProblemDetails responses, request-body CEL policies, JSON projection/redaction straight into Utf8JsonWriter, and OpenAPI 3.0 "nullable": true schema support. Longer term, a compile-time Roslyn analyzer to validate constant CEL literals in the IDE and dynamic SELECT field-mask projection are both on the list.

If you try it out and hit an edge case or a database dialect quirk, open an issue.