在域类中约束字符串长度

Kla*_*sen 6 c# string domain-model

我有一个持久性无知域模型,它使用抽象存储库来加载域对象.我的存储库(数据访问层(DAL))的具体实现使用实体框架从sql server数据库中获取数据.数据库对其许多varchar列具有长度限制.现在假设我有以下域类:

public class Case
{
    public Case(int id, string text)
    {
         this.Id = id;
         this.Text = text;
    }

    public int Id { get; private set; }
    public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并且抽象存储库定义如下:

public abstract class CaseRepository
{
    public abstract void CreateCase(Case item);
    public abstract Case GetCaseById(int id);
}
Run Code Online (Sandbox Code Playgroud)

[text]sqlserver中表的列定义为nvarchar(100)

现在我知道我提到我的域类(Case)是持久性无知的,但我觉得它允许text参数的值最终无法通过我的具体存储库实现保存是错误的,因为实体框架将抛出​​异常时当text属性超过100个字符时,将属性分配给实体框架生成的类.所以我决定在域模型中检查这个约束,因为这允许我在尝试将数据传递给DAL之前检查数据有效性,从而使错误报告更加中心到域对象.我想你可以说我可以在我的构造函数和属性setter中检查约束,但由于我有数百个类都有类似的约束,我想要一个更通用的方法来解决问题

现在,我想出的是一个叫做的类ConstrainedString,定义如下:

public abstract class ConstrainedString
{
    private string textValue;

    public ConstrainedString(uint maxLength, string textValue)
    {
        if (textValue == null) throw new ArgumentNullException("textValue");
        if (textValue.Length > maxLength) 
            throw new ArgumentException("textValue may not be longer than maxLength", "textValue");

        this.textValue = textValue;
        this.MaxLength = maxLength;
    }

    public uint MaxLength { get; private set; }

    public string Value 
    { 
        get 
        {
            return this.textValue;
        } 

        set 
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.Length > this.MaxLength) throw new ArgumentException("value cannot be longer than MaxLength", "value");
            this.textValue = value;
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我有一个ConstrainedString名为的实现String100:

public class String100 : ConstrainedString
{
    public String100(string textValue) : base(100, textValue) { }
}
Run Code Online (Sandbox Code Playgroud)

因此导致不同的实现Case看起来像这样:

public class Case
{
    public Case(int id, String100 text)
    {
         this.Id = id;
         this.Text = text;
    }

    public int Id { get; private set; }
    public String100 Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,我的问题是; 我是否可以忽略一些内置类或其他可以使用的方法?或者这是一种合理的方法吗?

任何意见和建议都是最受欢迎的.

先感谢您

Bro*_*n98 1

我相信您的验证应该驻留在您的域模型中。字段上的约束直接代表一些业务逻辑。最终你必须在坚持之前进行验证。