1
對於這個例子,我有兩個類是針對LINQ-to-SQL模型類的部分類。是否有另一種方法爲LINQ-to-SQL模型類創建合同?
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");
}
}
我想考慮此因素的功能以去除冗餘邏輯。我試着用IModel接口,然後擴展方法的合同,但它與分部類失效。
我結束了與此:
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
}
}
我應該這樣做另一種方式?謝謝。
「您可能對刪除的更新或插入的驗證規則不同」,不錯 – blu 2009-06-24 02:00:26