说说底层架构之实体类的设计
今天有点时间,来说说如何设计的实体类更加合理,灵活,规范.
首先,那要和真实数据表一一对应,必要的话,可以对类型抽象化,可以引入枚举,泛型列表等类型;其次,对实体要集成它的数据有效性的验证功能;再次,为了数据操作方便,有必要去引入数据表字段的列举集合;综上所述,我们来设计一个用户表实体;
本例中的知识点为:部分类,接口规范,Flag属性的枚举,迭代器等
/// <summary>
/// 数据实体统一接口
/// </summary>
public interface IDataEntity
{
}
/// <summary>
/// 用户实体
/// </summary>
partial class UserBase : IDataEntity
{
public string UserName { get; set; }
public int Age { get; set; }
}
/// <summary>
/// 实体验证类
/// </summary>
public class RuleViolation
{
/// <summary>
/// 错误属性
/// </summary>
public string ErrProperty { get; private set; }
/// <summary>
/// 错误信息
/// </summary>
public string ErrMessage { get; private set; }
public RuleViolation(string errProperty, string errMessage)
{
this.ErrProperty = errProperty;
this.ErrMessage = errMessage;
}
public RuleViolation(string errMessage)
: this(errMessage, null)
{
}
}
/// <summary>
/// 实体验证统一接口
/// </summary>
public interface IEntity
{
/// <summary>
/// 验证是否通过
/// </summary>
bool IsValid { get; }
/// <summary>
/// 以迭代的形式返回验证列表
/// </summary>
/// <returns></returns>
IEnumerable<RuleViolation> GetRuleViolations();
}
/// <summary>
/// 用户实体验证
/// </summary>
public partial class UserBase : IEntity
{
#region IEntity Members
public bool IsValid
{
get { return this.GetRuleViolations().Count() == 0; }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (string.IsNullOrEmpty(this.UserName))
yield return new RuleViolation("UserName", "用户名为能为空");
if (this.Age == 0)
yield return new RuleViolation("Age", "没有年龄为0的数据,至少为1");
}
#endregion
}
/// <summary>
/// 表字段列举
/// </summary>
[Flags]
public enum UserBaseColumns
{
UserName = 1,
Age = 2,
}