Skip to content

Instantly share code, notes, and snippets.

@maca88
Last active October 24, 2016 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maca88/20c4903965810c025d8ae3a2e7a5633a to your computer and use it in GitHub Desktop.
Save maca88/20c4903965810c025d8ae3a2e7a5633a to your computer and use it in GitHub Desktop.
FluentValidation using RootContextData
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1 {
using FluentValidation;
using FluentValidation.Results;
public class ParentEntity {
public string Code { get; set; }
public List<ChildEntity> Children { get; set; } = new List<ChildEntity>();
}
public class ChildEntity {
public string Code { get; set; }
}
public class ParentEntityValidator : AbstractValidator<ParentEntity> {
public ParentEntityValidator() {
RuleFor(o => o.Children).SetCollectionValidator(new ChildEntityValidator());
RuleFor(o => o.Code)
.Must((entity, code, ctx) => {
return ctx.ParentContext.RootContextData.Any(); // Not working
})
.WithMessage("ParentEntityValidator.RuleFor(o => o.Code).Must");
Custom((entity, ctx) => {
return ctx.RootContextData.Any() // Here it works!
? null
: new ValidationFailure("", "ParentEntityValidator.Custom");
});
}
}
public class ChildEntityValidator : AbstractValidator<ChildEntity> {
public ChildEntityValidator() {
RuleFor(m => m.Code)
.Must((entity, code, ctx) => {
return ctx.ParentContext.RootContextData.Any(); // Not working
})
.WithMessage("ChildEntityValidator.RuleFor(m => m.Code).Must");
Custom((entity, ctx) => {
return ctx.RootContextData.Any() // Not working
? null
: new ValidationFailure("", "ChildEntityValidator.Custom");
});
}
}
class Program {
static void Main(string[] args) {
// Create entities to validate
var parent = new ParentEntity();
for (var i = 0; i < 1; i++) {
parent.Children.Add(new ChildEntity {Code = $"Code{i}"});
}
// Custom data
var data = new HashSet<string>();
// Sync
var rootCtx = new ValidationContext<ParentEntity>(parent);
rootCtx.RootContextData.Add("data", data);
var result = new ParentEntityValidator().Validate(rootCtx);
if (!result.IsValid) {
// Does not work
}
// Async
result = new ParentEntityValidator().ValidateAsync(rootCtx).Result;
if (!result.IsValid) {
// Does not work
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment