c# - FluentValidation SetCollectionValidator for derived types -
How do I set assumptions on the collection types of derivative types? Just wondering ... Is this a way to insert it as a special type You can use conditional rows of rules to validate the collection, In which the various derivative objects type. Assume that your next class hierarchy is: and The main idea is to create a validating class, which is responsible for all class hierarchy recognition: and register this class as a collection object validator:
RuleFor (x = & gt; x.ComeCollection) .CastTo (SomeDerivedType) SetCollectionValidator (New SomeDerivedValidator ());
public class BaseClass {public string name {get; Set; }} Public class DerivedClassOne: Base class {public int count {get; Set; }} Public Category DerivedClassTwo: Base Class {Public Double Value {get; Set; }}
BaseClass container class with collection of items:
public class ContainerClass {public list & lt; BaseClass & gt; Collection {Received; Set; }}
public class CommonBaseClassValidator: AbstractValidator & lt; BaseClass & gt; {General CommonBaseClassValidator () {// General rules for all base class types RuleFor (x = & gt; x.Name) NotEmpty (); // Special rule for base when (model => model.GetType () == type (base class), () => gt; {RuleFor (x = & gt; x.Name). Lambic (0, 10); / / add rule here}}; // Special rules for derivative types when (model = & gt; models. GetType () == type (DerivedClassOne), () = & gt; {RuleFor (model = & gt; (DerivedClassOne) model). , 9), // add rule here}}; When (model = & gt; model.GetType () == type (DerivedClassTwo), () => {RuleFor (model => (DerivedClassTwo) model) .pice) .GreaterThan (1000); // Add rules here}}; }}
public class container wizard: abbetvilidetter & lt; Container Class & gt; {Public container () {RuleFor (model = & gt; model.Collection). SetCollectionValidator (New CommonBaseClassValidator ()); }}
Comments
Post a Comment