Skip to content

LINQ Support

Aryeh Citron edited this page May 12, 2026 · 3 revisions

LINQ Support

Overview

InMemoryEmulator.MongoDB supports LINQ queries via GetItemLinqQueryable<T>() / AsQueryable(). The MongoDB .NET Driver translates LINQ expressions into aggregation pipeline operations, which the emulator then evaluates.

LINQ2 vs LINQ3

The MongoDB .NET Driver supports two LINQ providers:

Feature LINQ2 LINQ3
Default in Driver < 2.19 Driver ≥ 2.19
Translation target $match / $project Full aggregation pipeline
StringComparison support Limited Full
DateTimeOffset support Limited Full

The InMemoryEmulator evaluates the rendered aggregation pipeline, so both LINQ2 and LINQ3 output work as long as the rendered operators are supported.

Supported Operations

Basic Queries

var queryable = collection.AsQueryable();

// Where
var results = queryable.Where(x => x.Status == "active").ToList();

// OrderBy
var sorted = queryable.OrderBy(x => x.Name).ToList();

// First / Single
var first = queryable.First(x => x.Id == someId);

// Count
var count = queryable.Count(x => x.IsActive);

Projections

var names = queryable.Select(x => new { x.Name, x.Email }).ToList();

Aggregation

var grouped = queryable
    .GroupBy(x => x.Category)
    .Select(g => new { Category = g.Key, Count = g.Count(), Total = g.Sum(x => x.Price) })
    .ToList();

Skip / Take

var page = queryable.OrderBy(x => x.Name).Skip(20).Take(10).ToList();

Known Differences

Area Behavior
StringComparison LINQ2 may not translate some StringComparison overloads; prefer LINQ3
Nullable<T> comparisons Edge cases in null propagation may differ between LINQ providers
Complex nested projections Very deep projections may evaluate differently
IQueryable extensions Custom extension methods not recognized by the driver won't translate

Tips

  1. Use LINQ3 (the default in driver ≥ 2.19) for the broadest operator support
  2. Use AsQueryable() instead of GetItemLinqQueryable() for simpler syntax
  3. For complex queries, prefer the fluent builder API (Builders<T>.Filter / .Update) over LINQ — it maps directly to MongoDB operators without translation

See Also

Clone this wiki locally