InvalidCastException when using ForEach rule
See original GitHub issueFluentValidation 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:
- Created 2 years ago
- Comments:10 (7 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ve published the 10.1 release to nuget with this fix.
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 toForEach
, but for all other scenarios this will fix the issue. The use ofConfigure
will need to wait until 11.I’ll let you know once this is pushed to nuget so you can give it a try.