OrchardCMS/OrchardCore · error · InvalidOperationException

Error converting value

Error message

Error converting value "{0}" to "{1}" for switch "{2}"

What it means

The switch value string is converted to the property's target type via ConvertToType; if conversion fails (FormatException/InvalidCastException etc.), the handler wraps it in this message including the raw value, target type, and switch name. It surfaces type errors from the CLI surface, e.g. passing "abc" to a bool switch.

Solutions

  1. Fix the command-line value so it parses as the property type shown in the message.
  2. Convert booleans with true/false and enums with exact member names.
  3. If you own the handler, validate/normalize the raw string, or change the property type to string and parse leniently yourself.
  4. Check culture: run with invariant parsing or use culture-neutral formats for numbers/dates.

Example fix

// before
mycommand -count abc
// after
mycommand -count 42
Defensive patterns

Strategy: validation

Validate before calling

if (!int.TryParse(rawValue, out var count)) throw new FormatException($"Value '{rawValue}' is not a valid integer for switch '{switchName}'");

Try / catch

try { await handler.ExecuteAsync(context); }
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Error converting value")) { logger.LogError(ex, "Switch value type error: {Message}", ex.Message); }

Prevention

When it happens

Trigger: Passing a value that cannot be parsed by the property type in SetSwitchValue: non-numeric text for an int property, an unparseable string for bool/enum/DateTime, or empty value for a required numeric switch.

Common situations: Shell scripts passing unvalidated variables into commands, culture-sensitive date/number formats, or users quoting values incorrectly.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs:61

        {
            throw new InvalidOperationException(S["A property \"{0}\" exists but is not decorated with \"{1}\"", commandSwitch.Key, nameof(OrchardSwitchAttribute)]);
        }

        // Set the value.
        try
        {
            var value = ConvertToType(propertyInfo.PropertyType, commandSwitch.Value);
            propertyInfo.SetValue(this, value, null /*index*/);
        }
        catch (Exception ex) when (!ex.IsFatal())
        {
            // TODO: (ngm) fix this message.
            var message = S["Error converting value \"{0}\" to \"{1}\" for switch \"{2}\"",
                commandSwitch.Value,
                propertyInfo.PropertyType.FullName,
                commandSwitch.Key];

            throw new InvalidOperationException(message, ex);
        }
    }

    private async Task InvokeAsync(CommandContext context)
    {
        CheckMethodForSwitches(context.CommandDescriptor.MethodInfo, context.Switches);

        var arguments = (context.Arguments ?? []).ToArray();
        var invokeParameters = GetInvokeParametersForMethod(context.CommandDescriptor.MethodInfo, arguments)
            ?? throw new InvalidOperationException(S["Command arguments \"{0}\" don't match command definition", string.Join(" ", arguments)]);

        Context = context;

        if (context.CommandDescriptor.MethodInfo.ReturnType == typeof(Task<string>))
        {
            var taskResult = await (Task<string>)context.CommandDescriptor.MethodInfo.Invoke(this, invokeParameters);
            await context.Output.WriteAsync(taskResult);
            return;

View on GitHub (pinned to 4306c0717f)