Transform doen't work for RuleForEach
See original GitHub issueVersion of FluentValidation: 9.0.0
.NET Framework 4.7
Description
Given the following code (which compiles fine) I’d expect Transform
will be applied for each collection member.
class ModelWithCollection {
public List<int> Collection { get; } = new List<int>() { 1, 2, 3, 4 };
}
class Validator : AbstractValidator<ModelWithCollection> {
public Validator() {
RuleForEach(model => model.Collection).Transform(i => i.ToString()).NotEqual("3");
}
}
But in runtime call new Validator().Validate(new ModelWithCollection())
thows an exception
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Int32'.'
This occurs in FluentValidation.Internal.Extensions.CoerceToNonGeneric<T, TProperty>
.
Obviously, Transform
behaves the same way for simple property and for collection rules, so in this case it gets whole collection as input, but inner function expects collection element.
I’d expect Transfom
either fail to compile in this case, or clearly state it will work with collection, or work with each separate element.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Thanks for reporting, that looks like a bug. Ideally when used with RuleForEach it should work against the collection elements (while it would work against the whole collection when used with RuleFor). I’ll look at this as part of the 9.1 release.
9.1 is now available on nuget with this change.