我有一个实现接口 IValidatable 的 IEntity 接口
public interface IValidatable {
bool IsValid { get; }
bool IsValidForPersistence { get; }
// Rules applied at UI time (please enter your name, etc)
IEnumerable<RuleViolation> GetRuleViolations();
// Rules to be applied only at persistence time
IEnumerable<RuleViolation> GetPersistenceRuleViolations();
}
public interface IEntity : IValidatable {
int ID { get; set; }
}
并且为了方便起见,我已经实现了我的 Entity 类,例如:
public abstract class Entity : IEntity {
public virtual int ID { get; set; }
public virtual bool IsValid {
get { return RuleViolations().Count() == 0; }
}
public virtual bool IsValidForPersistence {
get { return PersistenceRuleViolations().Count() == 0; }
}
public virtual IEnumerable<RuleViolation> GetRuleViolations() {
return new List<RuleViolation>();
}
public virtual IEnumerable<RuleViolation> GetPersistenceRuleViolations() {
return new List<RuleViolation>();
}
}
默认情况下,实体是有效的,直到 GetRuleViolations() 或 GetPersistenceRuleViolations() 被覆盖。
public partial class Company {
public override IEnumerable<RuleViolation> GetRuleViolations() {
if (String.IsNullOrEmpty(CompanyName))
yield return new RuleViolation("CompanyName", "Name is required.");
}
public override IEnumerable<RuleViolation> GetPersistenceRuleViolations() {
// Include standard rules too
foreach (RuleViolation rule in RuleViolations) {
yield return rule;
}
// Check some data based on a referenced entity "Bid"
if (!Active && Bid.Active)
yield return new RuleViolation("Active",
"When Active is set to false, the Bid must also be inactive.");
}
}
我知道这对于验证来说有点幼稚,所以除了任何错别字之外,还有什么可以改进的?