I have two classes, for this example, that are partial classes against LINQ-to-SQL model classes.
public partial class Foo
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
yield break;
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
public partial class Bar
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
yield break;
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
I'd like to factor this functionality out to remove the redundant logic. I tried it with an IModel interface and then extension methods for contracts but it broke down with the partial class.
I ended up with this:
public class ModelBase
{
public bool IsValid
{
get
{
return this.GetRuleViolations().Count() == 0;
}
}
public void OnValidate(ChangeAction action)
{
if (!IsValid) throw new ApplicationException("Rule violations prevent saving");
}
public virtual IEnumerable<RuleViolation> GetRuleViolations() { return null; }
}
public partial class Blog : ModelBase
{
partial void OnValidate(ChangeAction action)
{
base.OnValidate(action);
}
public override IEnumerable<RuleViolation> GetRuleViolations()
{
// rules omitted
}
}
Should I do this another way? Thank you.