C#-CustomAttribute和泛型约束 应用于经典数据处理适配
时间:2011-01-14 来源:下一个自己
该通用数据处理对象,我只实现个sqlserver的,反正自己的东西一般用这个,免得再来个工厂麻烦。
实现方式简单罗列下:
1、数据处理适配器的泛型T,加约束继承接口,需要实现PrimaryKeyName和实体索引,约束需要可以实例化即new();
2、实现表信息属性类,继承Attribute,可以作为CustomAttribute,在需要用的类的类名申明的上面以方括号的形式给该用户属性赋值。
方便使用数据库适配器与实体的解耦合,直接传递泛型对象实现所有其增删改查的数据操作功能。
3、数据处理适配器里面解析CustomAttribute出来获取表名以及字段信息,就方便进行select\update\insert等,完善查询的方法,可能有事务处理的再加上对应的事务处理重载方法。
不知有没好建议和意见,欢迎指出。
简单示例代码如下: public interface ITableModel { string PrimarkKeyName { get ; set; } object this [string name] { get; set ; } } public class TableInfoAttribute: Attribute { public string TableName { get; set; } public string [] Fileds { get; set; } } [ TableInfo(TableName = "ArticleCategories_TB" , Fileds = new string[] { "AutoID","ParentID" ,"CName", "Remark" })] public class ArticleCategoriesInfo : ITableModel { public int AutoID { get; set; } ......
public string PrimarkKeyName { get { return "AutoID" ; } set { PrimarkKeyName = value; } }
public object this[ string name] { get { switch (name.ToLower()) { ...... } } set { switch (name.ToLower()) { ...... } } } } //数据处理适配器 请注意where后面的约束 public class SqlDAL<T> where T:ITableModel ,new() { private static TableInfoAttribute GetTableInfo() { Type tType = typeof (T); object[] objs = tType.GetCustomAttributes(false); TableInfoAttribute tableInfo = objs[1] as TableInfoAttribute; return tableInfo; } public static T Select(int id) { T t = new T(); TableInfoAttribute tableInfo = GetTableInfo(); string sqlStr = string .Format("select * from {0} where {1}={2}",tableInfo.TableName,t.PrimarkKeyName,id); using (SqlDataReader idr = SqlHelper.ExecuteReader(ConnectionStr, CommandType.Text, sqlStr)) { while (idr.Read()) { for (int i = 0; i < idr.FieldCount; i++) { t[tableInfo.Fileds[i]] = idr[tableInfo.Fileds[i]]; } } } return t; } public static void Update(T t) { }
public static void Insert(T t) {
}
public static void Delete(T t) {
} public static void Update(T t, SqlTransaction tran) {
} public static void Insert(T t, SqlTransaction tran) { } public static void Delete(T t, SqlTransaction tran) {
} }
相关阅读 更多 +
排行榜 更多 +