我有一个持久性无知的域模型,它使用抽象存储库来加载域对象。我的存储库(数据访问层 (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; }
}
以及定义如下的抽象存储库:
public abstract class CaseRepository
{
public abstract void CreateCase(Case item);
public abstract Case GetCaseById(int id);
}
sqlserver中表的[text]
列定义为nvarchar(100)
现在我知道我提到我的域Case
类text
(分配text
超过 100 个字符时,实体框架生成的类的属性。所以我决定在域模型中检查这个约束,因为这允许我在尝试将数据传递给 DAL 之前检查数据的有效性,从而使错误报告更加集中于域对象。我想你可能会争辩说我可以只检查构造函数和属性设置器中的约束,但是由于我有数百个类都有类似的约束,我想要一种更通用的方法来解决问题
现在,我想出的是一个名为 的类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;
}
}
}
此外,我有一个ConstrainedString
调用的实现String100
:
public class String100 : ConstrainedString
{
public String100(string textValue) : base(100, textValue) { }
}
因此导致不同的实现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; }
}
现在,我的问题是;我是否忽略了一些内置类或我可以使用的其他方法?或者这是一个合理的方法?
欢迎任何意见和建议。
先感谢您