反射+泛型+缓存 ASP.NET的数据层通用类
一点想法+一点尝试
还有些问题有待解决^_^
还有些问题有待解决^_^
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection ;
using System.Data ;
using BaiChang.HealBlog.Model ;
using System.Data.SqlClient;
using BaiChang.SqlDBUtility;
namespace BaiChang.Middle.Front
{
public class DataAccess<T>where T:new()
{
Main Part#region Main Part
public static DataAccess<T> GetDataAccess()
{
string name = "DataAccess" + typeof(T).Name;
DataAccess<T> tObj = Utils.CurrentPage.Cache[name] as DataAccess<T>;
object obj = new object();
if (tObj == null)
{
Utils.CurrentPage.Cache[name] = typeof(DataAccess < T>).Assembly.CreateInstance(typeof(DataAccess<T>).Name);
tObj = Utils.CurrentPage.Cache[name] as DataAccess<T>;
}
return tObj;
}
public static string ToSetString(string name)
{
string formate = "{0}={1}";
return string.Format(formate, name, name);
}
public static List<T> ToModel(SqlDataReader reader)
{
Dictionary<string, PropertyInfo> ps = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo p in typeof (T).GetProperties ())
{
ps.Add(p.Name, p);
}
List<T> ms=new List<T> ();
while (reader.Read())
{
T m = new T();
object[] objs = null;
int count = reader.GetValues(objs);
int i = 0;
foreach (object o in objs)
{
ps[reader.GetName(i)].SetValue(m, o, null);
i++;
}
ms.Add(m);
}
return ms;
}
Properties#region Properties
//当前实体类型
Type entityType;
Type type
{
get
{
if(entityType ==null)
entityType = typeof(T);
return entityType;
}
}
//实体的所有属性
PropertyInfo[] propertyInfos;
PropertyInfo[] pros
{
get
{
if (propertyInfos == null) propertyInfos = this.type.GetProperties();
return propertyInfos;
}
}
//相对应的表名
string _tableName=string.Empty ;
string tableName
{
get
{
if (_tableName == string.Empty)
{
string className = typeof(T).Name;
switch (className)
{
case "Users":
case "Role_Node_Permissions":
_tableName = "PE_" + className;
default:
_tableName = "HB_" + className;
}
}
}
}
#endregion
#endregion
成员方法#region 成员方法
/**//// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID(pros[0].Name , tableName);
}
/**//// <summary>
/// 得到最大值
/// </summary>
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from ");
strSql.Append(tableName);
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros[0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
/**//// <summary>
/// 增加一条数据
/// </summary>
public int Add(T model)
{
StringBuilder strSql = new StringBuilder();
strSql .Append ("insert into ");
strSql .Append (tableName );
strSql.Append(" (");
//生成XXXvalues(XXX)
int i=1;
foreach (PropertyInfo p in pros)
{
strSql .Append (p.Name );
if (i != pros.Length)
strSql.Append(",");
i++;
}
strSql.Append(") values (");
i = 1;
foreach (PropertyInfo p in pros)
{
strSql.Append("@");
strSql.Append(p.Name);
if (i != pros.Length)
strSql.Append(",");
i++;
}
strSql.Append(");select @@IDENTITY");
//生成sqlparameters
List<SqlParameter> sqlpars = new List<SqlParameter>();
foreach (PropertyInfo p in pros)
{
SqlParameter sp = new SqlParameter("@" + p.Name, p.GetValue(model, null));
sqlpars.Add(sp);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString(), sqlpars .ToArray ());
if (obj == null)
{
return 1;
}
else
{
return Convert.ToInt32(obj);
}
}
/**//// <summary>
/// 更新一条数据
/// </summary>
public void Update(T model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update ");
strSql .Append (tableName );
strSql .Append (" set ");
int i=1;
foreach (PropertyInfo p in pros)
{
strSql.Append(ToSetString(p.Name));
if(i!=pros.Length )
strSql .Append (",");
i++;
}
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
//生成sqlparameters
List<SqlParameter> sqlpars = new List<SqlParameter>();
foreach (PropertyInfo p in pros)
{
SqlParameter sp = new SqlParameter("@" + p.Name, p.GetValue(model, null));
sqlpars.Add(sp);
}
DbHelperSQL.ExecuteSql(strSql.ToString(), sqlpars .ToArray());
}
/**//// <summary>
/// 删除一条数据
/// </summary>
public void Delete(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from ");
strSql.Append(tableName);
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros [0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
}
/**//// <summary>
/// 得到一个对象实体
/// </summary>
public T GetModel(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 ");
int i=1;
foreach (PropertyInfo p in pros)
{
strSql.Append(ToSetString(p.Name));
if(i!=pros.Length )
strSql .Append (",");
}
strSql .Append (tableName );
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros[0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString (), parameters))
{
ms= ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms[0];
else return default (T);
}
/**//// <summary>
/// 获得数据列表
/// </summary>
public List<T> GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * ");
strSql.Append(" FROM ");
strSql.Append(tableName);
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString ()))
{
ms = ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms;
else return null;
}
/**//// <summary>
/// 获得前几行数据
/// </summary>
public List<T> GetList(int Top, string strWhere, string filedOrder)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select ");
if (Top > 0)
{
strSql.Append(" top " + Top.ToString());
}
strSql.Append(" * ");
strSql.Append(" FROM ");
strSql.Append(tableName);
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
strSql.Append(" order by " + filedOrder);
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString ()))
{
ms = ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms;
else return null;
}
/**////<summary>
///分页获取数据列表
///</summary>
public List<T> GetList(int PageSize,int PageIndex,string strWhere)
{
List<T> ms=GetList(strWhere);
int startIndex=0, endIndex=0;
Utils.GetPageArea(ref startIndex, ref endIndex, PageIndex, PageSize, ms.Count);
List<T> result = new List<T>();
for (int i = startIndex; i <= endIndex; i++)
{
result.Add(ms[i]);
}
return result;
}
#endregion 成员方法
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection ;
using System.Data ;
using BaiChang.HealBlog.Model ;
using System.Data.SqlClient;
using BaiChang.SqlDBUtility;
namespace BaiChang.Middle.Front
{
public class DataAccess<T>where T:new()
{
Main Part#region Main Part
public static DataAccess<T> GetDataAccess()
{
string name = "DataAccess" + typeof(T).Name;
DataAccess<T> tObj = Utils.CurrentPage.Cache[name] as DataAccess<T>;
object obj = new object();
if (tObj == null)
{
Utils.CurrentPage.Cache[name] = typeof(DataAccess < T>).Assembly.CreateInstance(typeof(DataAccess<T>).Name);
tObj = Utils.CurrentPage.Cache[name] as DataAccess<T>;
}
return tObj;
}
public static string ToSetString(string name)
{
string formate = "{0}={1}";
return string.Format(formate, name, name);
}
public static List<T> ToModel(SqlDataReader reader)
{
Dictionary<string, PropertyInfo> ps = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo p in typeof (T).GetProperties ())
{
ps.Add(p.Name, p);
}
List<T> ms=new List<T> ();
while (reader.Read())
{
T m = new T();
object[] objs = null;
int count = reader.GetValues(objs);
int i = 0;
foreach (object o in objs)
{
ps[reader.GetName(i)].SetValue(m, o, null);
i++;
}
ms.Add(m);
}
return ms;
}
Properties#region Properties
//当前实体类型
Type entityType;
Type type
{
get
{
if(entityType ==null)
entityType = typeof(T);
return entityType;
}
}
//实体的所有属性
PropertyInfo[] propertyInfos;
PropertyInfo[] pros
{
get
{
if (propertyInfos == null) propertyInfos = this.type.GetProperties();
return propertyInfos;
}
}
//相对应的表名
string _tableName=string.Empty ;
string tableName
{
get
{
if (_tableName == string.Empty)
{
string className = typeof(T).Name;
switch (className)
{
case "Users":
case "Role_Node_Permissions":
_tableName = "PE_" + className;
default:
_tableName = "HB_" + className;
}
}
}
}
#endregion
#endregion
成员方法#region 成员方法
/**//// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID(pros[0].Name , tableName);
}
/**//// <summary>
/// 得到最大值
/// </summary>
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from ");
strSql.Append(tableName);
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros[0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
/**//// <summary>
/// 增加一条数据
/// </summary>
public int Add(T model)
{
StringBuilder strSql = new StringBuilder();
strSql .Append ("insert into ");
strSql .Append (tableName );
strSql.Append(" (");
//生成XXXvalues(XXX)
int i=1;
foreach (PropertyInfo p in pros)
{
strSql .Append (p.Name );
if (i != pros.Length)
strSql.Append(",");
i++;
}
strSql.Append(") values (");
i = 1;
foreach (PropertyInfo p in pros)
{
strSql.Append("@");
strSql.Append(p.Name);
if (i != pros.Length)
strSql.Append(",");
i++;
}
strSql.Append(");select @@IDENTITY");
//生成sqlparameters
List<SqlParameter> sqlpars = new List<SqlParameter>();
foreach (PropertyInfo p in pros)
{
SqlParameter sp = new SqlParameter("@" + p.Name, p.GetValue(model, null));
sqlpars.Add(sp);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString(), sqlpars .ToArray ());
if (obj == null)
{
return 1;
}
else
{
return Convert.ToInt32(obj);
}
}
/**//// <summary>
/// 更新一条数据
/// </summary>
public void Update(T model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update ");
strSql .Append (tableName );
strSql .Append (" set ");
int i=1;
foreach (PropertyInfo p in pros)
{
strSql.Append(ToSetString(p.Name));
if(i!=pros.Length )
strSql .Append (",");
i++;
}
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
//生成sqlparameters
List<SqlParameter> sqlpars = new List<SqlParameter>();
foreach (PropertyInfo p in pros)
{
SqlParameter sp = new SqlParameter("@" + p.Name, p.GetValue(model, null));
sqlpars.Add(sp);
}
DbHelperSQL.ExecuteSql(strSql.ToString(), sqlpars .ToArray());
}
/**//// <summary>
/// 删除一条数据
/// </summary>
public void Delete(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from ");
strSql.Append(tableName);
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros [0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
}
/**//// <summary>
/// 得到一个对象实体
/// </summary>
public T GetModel(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 ");
int i=1;
foreach (PropertyInfo p in pros)
{
strSql.Append(ToSetString(p.Name));
if(i!=pros.Length )
strSql .Append (",");
}
strSql .Append (tableName );
strSql.Append(" where ");
strSql.Append(ToSetString(pros[0].Name));
SqlParameter[] parameters = {
new SqlParameter("@"+pros[0].Name, SqlDbType.Int,4)};
parameters[0].Value = ID;
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString (), parameters))
{
ms= ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms[0];
else return default (T);
}
/**//// <summary>
/// 获得数据列表
/// </summary>
public List<T> GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * ");
strSql.Append(" FROM ");
strSql.Append(tableName);
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString ()))
{
ms = ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms;
else return null;
}
/**//// <summary>
/// 获得前几行数据
/// </summary>
public List<T> GetList(int Top, string strWhere, string filedOrder)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select ");
if (Top > 0)
{
strSql.Append(" top " + Top.ToString());
}
strSql.Append(" * ");
strSql.Append(" FROM ");
strSql.Append(tableName);
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
strSql.Append(" order by " + filedOrder);
List<T> ms;
using (SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql.ToString ()))
{
ms = ToModel(reader);
reader.Close();
}
if (ms.Count > 0) return ms;
else return null;
}
/**////<summary>
///分页获取数据列表
///</summary>
public List<T> GetList(int PageSize,int PageIndex,string strWhere)
{
List<T> ms=GetList(strWhere);
int startIndex=0, endIndex=0;
Utils.GetPageArea(ref startIndex, ref endIndex, PageIndex, PageSize, ms.Count);
List<T> result = new List<T>();
for (int i = startIndex; i <= endIndex; i++)
{
result.Add(ms[i]);
}
return result;
}
#endregion 成员方法
}
}