OrchardCMS/OrchardCore · error · InvalidCastException

Cannot convert to BigInteger.

Error message

Cannot convert {value.GetType()} to BigInteger.

What it means

This InvalidCastException is thrown by the private ToBigInteger helper (called from CompareBigInteger via Compare) when a numeric JSON value cannot be represented as a BigInteger — i.e. it is a double/decimal that is not an integer, or a type outside the handled set.

Solutions

  1. Ensure compared numeric values are integral (integers) before comparing
  2. Convert decimals/doubles to a common type and compare as double yourself
  3. Round/truncate to integer before comparing if the domain allows
  4. Compare strings ordinally as a fallback for uniform handling

Example fix

// before
items.OrderBy(x => x.Value) // 1 vs 2.5 hits BigInteger conversion
// after
items.OrderBy(x => Convert.ToDouble(x.Value?.GetObjectValue()))
Defensive patterns

Strategy: type-guard

Validate before calling

static bool IsIntegralNumber(object? v) => v is JsonElement el &&
    el.ValueKind == JsonValueKind.Number &&
    (el.TryGetInt64(out _) || el.TryGetUInt64(out _));

Type guard

static bool IsBigIntegerSafe(JsonDynamicValue? v) =>
    v?.GetObjectValue() is JsonElement el && el.ValueKind == JsonValueKind.Number &&
    el.TryGetInt64(out _);

Try / catch

int cmp;
try { cmp = a.CompareTo(b); }
catch (InvalidCastException ex) { /* log, compare as double */
    cmp = Convert.ToDouble(a?.GetObjectValue()).CompareTo(Convert.ToDouble(b?.GetObjectValue())); }

Prevention

When it happens

Trigger: Comparing JsonDynamicValue numeric values where one side is a non-integral number (e.g. 3.14) and the comparison path needs BigInteger conversion; comparing very large doubles with integers.

Common situations: Sorting JSON numbers that mix integers and decimals (e.g. [1, 2.5, 3]); comparing price fields (decimals) against integer quantities.

Understand the failure class

Background: "is not a compatible type" / "cannot merge" errors: when a value's type doesn't match what the library requires — this error's family across 65 libraries.

Related errors


AI-assisted analysis of OrchardCMS/OrchardCore@4306c0717f (2026-09-13). Data as JSON: /api/errors/70950bad3ed428f9. Report an issue: GitHub.

Appendix: source

Thrown at src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicValue.cs:810

            if (value is long l)
            {
                return new BigInteger(l);
            }
            if (value is uint u)
            {
                return new BigInteger(u);
            }
            if (value is ulong @ulong)
            {
                return new BigInteger(@ulong);
            }

            if (value is byte[] bytes)
            {
                return new BigInteger(bytes);
            }

            throw new InvalidCastException($"Cannot convert {value.GetType()} to BigInteger.");
        }
    }
}

View on GitHub (pinned to 4306c0717f)