对于需求中的不要暴露DataTable或DataSet,我想到了设计中常用的对象:实体(Entity),通过实体将数据库中的字段封装成类,这样做不仅使代码更有可读性,维护起来也很方便。同时我自定义了一些C#特性来表述字段在数据库中的特性。
1.递增键:
1 namespace RA.DataAccess.Attributes 2 { 3 /// <summary> 4 /// 递增键 5 /// </summary> 6 [AttributeUsage(AttributeTargets.Property, Inherited = true)] 7 public class IdentityAttribute:Attribute 8 { 9 } 10 }
2.主键:
1 namespace RA.DataAccess.Attributes 2 { 3 /// <summary> 4 /// 主键 5 /// </summary> 6 [AttributeUsage(AttributeTargets.Property, Inherited = true)] 7 public class PrimaryAttribute : Attribute 8 { 9 10 } 11 }
3.表名:
1 namespace RA.DataAccess.Attributes 2 { 3 /// <summary> 4 /// 表名 5 /// </summary> 6 [AttributeUsage(AttributeTargets.Class, Inherited = true)] 7 public class TableNameAttribute : Attribute 8 { 9 public string TableName { get; set; } 10 11 public TableNameAttribute(string name) 12 { 13 TableName = name; 14 } 15 } 16 }
测试用例:
1 namespace RA.MyBlog.Entity 2 { 3 4 [TableName("RA_MyBlog_Article")] 5 public class ArticleEntity 6 { 7 [Primary] 8 [Identity] 9 //文章ID 10 public int articleID { get; set; } 11 //分类ID 12 public int categoryID { get; set; } 13 //文章标题 14 public string articleTitle { get; set; } 15 //文章版权 16 public string articleCopyright { get; set; } 17 //文章创建时间 18 public DateTime articleDate { get; set; } 19 //文章摘要 20 public string articleAbstract { get; set; } 21 //文章内容 22 public string articleContain { get; set; } 23 //文章所属User 24 public int userID { get; set; } 25 } 26 }