【问题标题】:Is there another way to create a contract for a LINQ-to-SQL model class?是否有另一种方法可以为 LINQ-to-SQL 模型类创建契约?
【发布时间】:2009-06-24 00:59:04
【问题描述】:

对于本示例,我有两个类,它们是针对 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
    }
}

我应该以其他方式执行此操作吗?谢谢。

【问题讨论】:

    标签: asp.net-mvc linq-to-sql model repository


    【解决方案1】:

    我唯一要补充的是,您可能想要定义一个接口,然后是实现该接口的各种基类以提供一些默认验证。例如,您可能有一个基类对字符串属性进行 XSS 验证,验证它们不包含任何 HTML。使用接口将允许您从这些基类中的任何一个(或者甚至只是接口,如果您愿意)派生,并且仍然能够将它们视为接口。您还可以考虑拥有一个允许您指定 ChangeAction 的签名——您可能对 Delete 的验证规则与 Update 或 Insert 的验证规则不同。

    public interface IValidatedEntity
    {
        IEnumerable<RuleViolations> GetRuleViolations();
        IEnumerable<RuleViolations> GetRuleViolations( ChangeAction action );
    }
    
    public abstract class XSSValidatedEntity : IValidatedEntity
    {
        public virtual IEnumerable<RuleViolations> GetRuleViolations()
        {
            return GetRuleViolations( ChangeAction.Insert );
        }
    
        public virtual IEnumerable<RuleViolations> GetRuleViolations( ChangeAction action )
        {
             if (action != ChangeAction.Delete)
             {
                 return ValidateStringProperties();
             }
             return new List<RuleViolations>();
        }
    }
    

    【讨论】:

    • “你可能有不同的删除验证规则,而不是更新或插入”,很好
    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多