question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

InvalidCastException when using ForEach rule

See original GitHub issue

FluentValidation version

10.0.4

ASP.NET version

.NET Core 3.1

Summary

I have a rulebuilder for a IList typed property with three rules: notEmpty, foreach and mustAsync. The problem is that the foreach rule returns a rulebuilder with out type ‘IEnumerable<TElement>’ but the next rule seems to expect the original property type IList since there is an invalid cast exception from …IList… to …IEnumerable…

This rule did not give any exception in FluentValidation version 9.3.0.

Steps to Reproduce

The code Dto to validate

    public class SaveRegistrationRequestForHardwareUnit : CommandWithTransactionToggle<SuccessOrFailureDto>
    {
        //other props
        public IList<KeyValuePair<Guid,string>> HardwareUnitRoles { get; set; }
    }

Validator

public class SaveRegistrationRequestForHardwareUnitValidator : AbstractValidator<SaveRegistrationRequestForHardwareUnit>
{
    private const string ValidRoleConfigMessage = "ValidRoleConfigMessage";

    public SaveRegistrationRequestForHardwareUnitValidator(IValidator<UserDto> userDtoValidator)
    {
        //Other rules

        RuleFor(r => r.HardwareUnitRoles).Cascade(CascadeMode.Stop)
            .NotEmpty()
            .ForEach(r => r
                .Must(kv => HardwareUnitUserRoles.IsValid(kv.Value))
                    .WithMessage(m => Resources.ValidationMessages.hardwareunit_role_notvalid)
                .Must(kv => kv.Value != HardwareUnitUserRoles.Owner)
                    .WithMessage(m => Resources.ValidationMessages.registrationrequest_hardwareUnitRole_notallowed)
            )
            .MustAsync((roles, token) => ValidRoleConfigAsync(roles))//GIVES EXCEPTION
                .WithMessage(dto => ValidationErrorMessages.GetErrorMessage(ValidRoleConfigMessage));
    }

    private async Task<bool> ValidRoleConfigAsync(IEnumerable<KeyValuePair<Guid, string>> hardwareUnitRoles)
    {
        //logic
    }
}

Exception:

System.InvalidCastException: Unable to cast object
of type 'FluentValidation.Internal.RuleBuilder`2[Foo.Commands.Registration.SaveRegistrationRequestForHardwareUnit,System.Collections.Generic.IList`1[System.Collections.Generic.KeyValuePair`2[System.Guid,System.String]]]'
to type 'FluentValidation.Internal.RuleBuilder`2[Foo.Commands.Registration.SaveRegistrationRequestForHardwareUnit,System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.Guid,System.String]]]'.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:10 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
JeremySkinnercommented, Apr 28, 2021

I’ve published the 10.1 release to nuget with this fix.

1reaction
JeremySkinnercommented, Apr 23, 2021

I’ve committed a change in 6e825d33 which will allow this to work in 10.x without needing to introduce breaking changes (adds an additional interface, which can be removed again in v11). Well, technically there is one breaking change to the return type of one undocumented public method (DefaultValidatorOptions.Configurable), but I think this is worth it to get the fix in place. I’ll try and get this pushed out to nuget over the weekend.

With this fix, the underlying problem will still be present if the user calls the Configure method following a call to ForEach, but for all other scenarios this will fix the issue. The use of Configure will need to wait until 11.

I’ll let you know once this is pushed to nuget so you can give it a try.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Foreach can throw an InvalidCastException?
With C# 3 I'm using var - so I get the compiler warnings. foreach works on IEnumerable, which returns objects of type object....
Read more >
[Solved] Invalid cast error (foreach loop)?
I've got this foreach loop: foreach (GameObject existingSlot in inventorySlots) {} "inventorySlots" is a Transform reference to a UI object.
Read more >
Possible 'System.InvalidCastException' in foreach loop
ReSharper wants you to be on the safe side and therefore notifies of possible System. InvalidCastException if it detects an unsafe cast like ......
Read more >
ASP.NET - System.InvalidCastException in foreach loop
Represents the error that occurs when an explicit conversion (casting operation) fails because the source type cannot be converted to the destination type....
Read more >
Casting and the foreach Statement : Mad Props! - Matt Hamilton
As a test, I tried adding an int to my array of object, and sure enough the code crashed at runtime with an...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found