litedb-org/LiteDB · error · NotSupportedException

The type BsonRefId<T> can only be used in LiteDB LINQ expres

Error message

The type BsonRefId<T> can only be used in LiteDB LINQ expressions.

What it means

Thrown by the implicit conversion operator BsonRefId<T> -> T. BsonRefId<T> is a marker type used only inside LiteDB LINQ expression trees (e.g. UpdateMany projections) to assign a DbRef id without loading the referenced entity. The implicit operator exists to satisfy the compiler but, if actually invoked at runtime, means the expression was not captured into a tree and processed by LiteDB's visitor.

Source

Thrown at LiteDB/Client/Mapper/BsonRefId.cs:31

///     {
///       Id = x.Id,
///       Bref = new BsonRefId&lt;B&gt;(100),
///     },
///     x => x.Id == 11);
/// </code></example>
public sealed class BsonRefId<T>
{
    /// <summary>
    /// Assigns the ID of the referenced entity of type <typeparamref name="T"/>.
    /// </summary>
    /// <param name="id">The ID to assign.</param>
    public BsonRefId(BsonValue id)
    {
    }

    public static implicit operator T(BsonRefId<T> _)
    {
        throw new NotSupportedException("The type BsonRefId<T> can only be used in LiteDB LINQ expressions.");
    }
}

View on GitHub (pinned to f906a5f850)

Solutions

  1. Use BsonRefId<T> only inside expression lambdas passed to LiteDB methods like UpdateMany.
  2. Ensure the lambda is typed as Expression<Func<T,T>> so it is captured as a tree, not compiled.
  3. To assign a reference id directly, set the navigation property to a real entity or update the foreign-key field by name instead.

Example fix

// before
var a = new A { Bref = new BsonRefId<B>(100) }; // runs the implicit operator -> throws

// after
db.GetCollection<A>().UpdateMany(
    x => new A { Id = x.Id, Bref = new BsonRefId<B>(100) }, // captured as Expression<Func<A,A>>
    x => x.Id == 11);
Defensive patterns

Strategy: validation

Validate before calling

// Only use BsonRefId inside an Expression<Func<T,T>> passed to LiteDB.
// Do not assign new BsonRefId<T>(id) to a property of type T outside an expression tree.

Prevention

When it happens

Trigger: Using new BsonRefId<B>(id) in code that is NOT a LINQ expression tree LiteDB interprets, e.g. assigning it directly to a property of type B, or constructing a projection that gets compiled and executed rather than translated. Materializing a query whose Select yields a BsonRefId and then implicitly converting also triggers it.

Common situations: Copy-pasting the UpdateMany example into a regular method body instead of an expression lambda, or trying to read back a BsonRefId-typed value into a concrete entity property at runtime.

Related errors


AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13). Data as JSON: /api/errors/d4a64324546d902f. Report an issue: GitHub.