c# - FluentValidation SetCollectionValidator for derived types -


How do I set assumptions on the collection types of derivative types? Class BaseClass {} Class DerivedClass: Base Class {} Class SomeClass {Public IEnumerable & lt; BaseClass & gt; Base Classes {Get; Set; }} Category DerivedClassValidator: abbetvilidetter & lt; DerivedClass & gt; {} Class SomeClassValidator: abbetvilidetter & lt; SomeClass & gt; {Public SomeClassValidator () {RuleFor (x = & gt; x.BaseClasses). Line SetCollectionValidator (New DerivedClassValidator); }}

Just wondering ...

Is this a way to insert it as a special type

  RuleFor (x = & gt; x.ComeCollection) .CastTo (SomeDerivedType) SetCollectionValidator (New SomeDerivedValidator ());  

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:

  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; }}   

and BaseClass container class with collection of items:

  public class ContainerClass {public list & lt; BaseClass & gt; Collection {Received; Set; }}   

The main idea is to create a validating class, which is responsible for all class hierarchy recognition:

  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}}; }}   

and register this class as a collection object validator:

  public class container wizard: abbetvilidetter & lt; Container Class & gt; {Public container () {RuleFor (model = & gt; model.Collection). SetCollectionValidator (New CommonBaseClassValidator ()); }}    

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -