- 特性与实体设计
对于需求中的不要暴露DataTable或DataSet,设计中常用的对象:实体(Entity),通过实体将数据库中的字段封装成类,这样做不仅使代码更有可读性,维护起来也很方便。
- 递增键
namespace RA.DataAccess.Attributes
{
/// <summary>
/// 递增键
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class IdentityAttribute:Attribute
{
}
}
- 主键
namespace RA.DataAccess.Attributes
{
/// <summary>
/// 主键
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class PrimaryAttribute : Attribute
{
}
}
- 表名
namespace RA.DataAccess.Attributes
{
/// <summary>
/// 表名
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class TableNameAttribute : Attribute
{
public string TableName { get; set; }
public TableNameAttribute(string name)
{
TableName = name;
}
}
}
思维导图:
- 实体,数据传输对象(DTO)Helper类设计
EntityHelper的主要功能
1.通过反射获取DTO的字段,主要提供给在需要从Entity获取数据后,填充给DTO并返回的作用:
通过反射获取PropertyInfo[]对象,然后取出Name属性,填入新表。
2.获取实体中的字段,主要提供在Select,Update,Insert,Join等中字段的获取,以及动态返回泛型TEntity时为反射构建Entity的对象时使用。通过反射获取PropertyInfo[],当isFullName为true时,使用GetTableName<T>方法获取实体表名,并将表名和字段名用'.'连接。
3.获取实体代表的数据表的表名,用于构建Sql时提供表名。前文已经介绍了自定义特性[TableName],此处就是使用这个特性反射出Entity代表的表名。
4.获取实体代表的数据表的主键。前面已经介绍了自定义特性[Primary],此处就是使用这个特性反射出Entity代表的表中的主键。
思维导图:
对象反射Helper类
ObjectHelper的主要功能
1.通过反射获取Entity的实例的字段值和表名,跳过自增键并填入Dictionary<string,string>中。
2.通过反射,为实例赋值,此处只是列举了常用的数据类型:int,string和DataTime。
思维导图:
范例:
namespace RA.MyBlog.Entity
{
[TableName("RA_MyBlog_Article")]
public class ArticleEntity
{
[Primary]
[Identity]
//文章ID
public int articleID { get; set; }
//分类ID
public int categoryID { get; set; }
//文章标题
public string articleTitle { get; set; }
//文章版权
public string articleCopyright { get; set; }
//文章创建时间
public DateTime articleDate { get; set; }
//文章摘要
public string articleAbstract { get; set; }
//文章内容
public string articleContain { get; set; }
//文章所属User
public int userID { get; set; }
}
}