CSLA验证规则总结
CSLA业务规则
验证规则所在空间: Csla.Rules
基类 BusinessBase 的属性 BusinessRules 中记录了业务类的验证规则
验证规格的写法
private class MyRule : Csla.Rules.BusinessRule
{
protected override void Execute(RuleContext context)
{
var target = (Customer)context.Target;
if (target.Sales < 10)
context.AddInformationResult("Customer has
low sales");
}
}
添加验证规则
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new MyRule { PrimaryProperty = SalesProperty
});
}
多数规则都需要设置一个主要属性(PrimaryProperty),在构造函数中中为其赋值,比如下面的 Required,MaxLength 规则
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new MyRule { PrimaryProperty = SalesProperty });
BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(NameProperty, 20));
}
引发验证规则
BusinessRules.AddRule(new MyRule { PrimaryProperty = SalesProperty });
在之前的AddRule() 调用中,PrimaryProperty 属性被设置为 SalesProperty,
把验证规格 和 特定的属性关联在一起,一旦属性(SalesProperty)变动,验证规则就会被自动触发。
如果没有提供 为验证规则提供PrimaryProperty,业务规则是和业务类进行关联的。
基类 BusinessBase 的属性 BusinessRules 中有三个方法来检查验证规格
1 、CheckRules() – 检查对象中的所有验证规则。
2、CheckObjectRules() - 仅校验不和属性关联的验证规则。
3、CheckRules(property) – 检查某个属性的所有规则。
框架中的实现
var rulesProperty
= typeof(BusinessBase).GetProperty("BusinessRules",BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
if (rulesProperty != null)
{
var rules = rulesProperty.GetValue(this.Basic, null) as Csla.Rules.BusinessRules;
if (rules != null)
{
rules.CheckRules();
}
}
else
{
messageService.ShowError("rulesProperty == null");
}
提示实效规则列表
实效列表 BrokenRulesCollection
if (this.Basic.BrokenRulesCollection.Count > 0)
{
string temp = string.Empty;
foreach (var item in this.Basic.BrokenRulesCollection)
{
temp += item.Description + "\r\n";
}
messageService.ShowError(temp);
return result;
}