Sunday 15 August 2010

c# - Fluent validation and Must custom validation -



c# - Fluent validation and Must custom validation -

i have class , validation looks this:

public validationresult validate(customertype customertype) { customertype validator validator = new customertypevalidator(); validator.rulefor(x => x.number).must(beuniquenumber); homecoming validator.validate(customertype); } public bool beuniquenumber(int number) { //var result = repository.get(x => x.number == customertype.number) // .where(x => x.id != customertype.id) // .firstordefault(); //return result == null; homecoming true; }

the customertypevalidator basic validator class validates string properties.

i add together new rule check if number unique in db. in class because there's reference repository. validator class has no such reference.

the problem here beuniquenumber method should have customertype parameter. when this, error on rulefor line above because 'must' needs int parameter.

is there way around this?

can seek this?

public validationresult validate(customertype customertype) { customertypevalidator validator = new customertypevalidator(); validator.rulefor(x => x).must(haveuniquenumber); homecoming validator.validate(customertype); } public bool haveuniquenumber(customertype customertype) { var result = repository.get(x => x.number == customertype.number) .where(x => x.id != customertype.id) .firstordefault(); homecoming result == null; //return true; }

you should able this:

public validationresult validate(customertype customertype) { customertypevalidator validator = new customertypevalidator(); validator.rulefor(x => x.number).must(beuniquenumber); homecoming validator.validate(customertype); } public bool beuniquenumber(customertype customertype, int number) { var result = repository.get(x => x.number == number) .where(x => x.id != customertype.id) .firstordefault(); homecoming result == null; //return true; }

"i add together new rule check if number unique in db. in class because there's reference repository."

well, why can't give validator reference repository too?

customertypevalidator validator = new customertypevalidator(repository);

c# fluentvalidation

No comments:

Post a Comment