This discussion talked about getting a parent context into each child validator in a collection:
RuleFor(workDay => workDay.WorkItems)
.SetCollectionValidator(workDay => new WorkItemValidator(workDay));
The idea in this example would be to check if each work item had been given an assignment by accessing the parents "WorkDay.Assignments" collection. I've come to realize that this isn't the solution I'm actually looking for. The validation should really occur on the Parent level treating each WorkItem as a property.
If the WorkItems collection was an array and was always a fixed size then I could do something like this and repeat for each index:
RuleFor(workDay => workDay.WorkItems[0]).Must((workDay, workItem) => {var assignedWorkItems = from assignment in workDay.Assignmentsselect assignment.WorkItem;return assignedWorkItems.Contains(workItem); }) .WithMessage("{0} has not been assigned", wi => wi.WorkItems[0].Description)
.WithName("WorkItems[0]");
However, usually we are working with a variable sized IEnumerable so this isn't possible.
Wondering if anyone has thoughts on a good way to achieve this or if this is a train wreck approach?
A couple ideas:
RuleForEach(workDay => workDay.WorkItems) .Must((workDay, workItem) => { ... });
RuleFor(workDay => workDay.Items) .ForEach((workDay, workItem) => { ... })
Cheers,
mike