Last active
October 24, 2016 19:57
-
-
Save maca88/20c4903965810c025d8ae3a2e7a5633a to your computer and use it in GitHub Desktop.
FluentValidation using RootContextData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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