在1的基础上做了一点改进 参数化处理 看上去更简洁 无主键情况下 update 方法需要改进 insert delete没有问题
/// <summary>
/// DAO基类 实体名必须要与数据表字段名一致
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseDao<T> where T : new()
{
protected DataModule dataModule = new DataModule();
/// <summary>
/// 表名
/// </summary>
public virtual string TableName { get; set; }
/// <summary>
/// 主键ID
/// </summary>
public virtual string PrimaryKey { get; set; }
/// <summary>
/// 实体属性
/// </summary>
private PropertyInfo[] properties = null;
/// <summary>
/// 实体类型
/// </summary>
private readonly Type t = typeof(T);
public BaseDao()
{
t = typeof(T);
properties = t.GetProperties();
}
public BaseDao(string tableName, string primaryKey)
: this()
{
this.TableName = tableName;
this.PrimaryKey = primaryKey;
}
public int GetMaxID()
{
string sql = "select max(cast(" + PrimaryKey + " as decimal(18,0))) as MaxId from " + TableName;
DataTable dt = dataModule.GetDataTable(sql);
if (dt.Rows[0][0] == DBNull.Value)
{
return 1;
}
else
{
return Convert.ToInt32(dt.Rows[0][0]) + 1;
}
}
/// <summary>
/// 清除实体字段
/// </summary>
/// <param name="entity"></param>
public void ClearT(ref T entity)
{
entity = default(T);
entity = new T();
}
/// <summary>
/// 获取实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetT(string id)
{
string sql = "select * from " + TableName + " where " + PrimaryKey + "='" + id + "'";
DataTable dt = dataModule.GetDataTable(sql);
T entity = new T();
return SetEntityValue(dt, entity);
}
/// <summary>
/// 根据多个条件获取实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T GetT(T entity)
{
StringBuilder sql = new StringBuilder("select * from " + TableName + " where ");
Hashtable ht = GetWhereConditionSQL(entity);
string where = ht["SQL"] as string;
sql.Append(where);
SqlParameter[] paras = ht["PAMS"] as SqlParameter[];
DataTable dt = dataModule.GetDataTable(sql.ToString(), paras);
return SetEntityValue(dt, entity);
}
/// <summary>
/// 保存
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public bool InsertT(T entity)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
if (!string.IsNullOrEmpty(PrimaryKey) && t.GetProperty(PrimaryKey).GetValue(entity, null) == null)
{
if (t.GetProperty(PrimaryKey).PropertyType == typeof(string))
{
t.GetProperty(PrimaryKey).SetValue(entity, GetMaxID().ToString(), null);
}
else
{
t.GetProperty(PrimaryKey).SetValue(entity, GetMaxID(), null);
}
}
sql.Append(" Insert into " + TableName + " ( ");
StringBuilder insertFields = new StringBuilder("");
StringBuilder insertValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
insertFields.Append("" + property.Name + ",");
insertValues.Append("@" + property.Name + ",");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
}
}
sql.Append(insertFields.ToString().TrimEnd(','));
sql.Append(" ) VALUES ( ");
sql.Append(insertValues.ToString().TrimEnd(','));
sql.Append(")");
return dataModule.ExcuteSql(sql.ToString(), paras.ToArray());
}
/// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool UpdateT(T entity)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
sql.Append(" update " + TableName + " set ");
StringBuilder updateValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
updateValues.Append(property.Name + "=@" + property.Name + ",");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
}
else
{
updateValues.Append(property.Name + "=null,");
}
}
sql.Append(updateValues.ToString().TrimEnd(','));
sql.Append(" where " + PrimaryKey + "=@" + PrimaryKey);
return dataModule.ExcuteSql(sql.ToString(), paras.ToArray());
}
/// <summary>
/// 更新指定字段
/// </summary>
/// <param name="entity"></param>
/// <param name="field">实体属性名称</param>
/// <returns></returns>
public bool UpdateT(T entity, string field)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
sql.Append(" update " + TableName + " set ");
StringBuilder updateValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
updateValues.Append(field + "=@" + field + " ");
paras.Add(new SqlParameter("@" + field, t.GetProperty(field).GetValue(entity, null)));
sql.Append(updateValues.ToString());
sql.Append(" where " + PrimaryKey + "=@" + PrimaryKey);
paras.Add(new SqlParameter("@" + PrimaryKey,t.GetProperty(PrimaryKey).GetValue(entity, null)));
return dataModule.ExcuteSql(sql.ToString(),paras.ToArray());
}
/// <summary>
/// 根据多个字段删除实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool DeleteT(T entity)
{
StringBuilder sql = new StringBuilder("delete from " + TableName + " where ");
Hashtable ht = GetWhereConditionSQL(entity);
string where = ht["SQL"] as string;
sql.Append(where);
SqlParameter[] paras = ht["PAMS"] as SqlParameter[];
return dataModule.ExcuteSql(sql.ToString(), paras);
}
/// <summary>
/// 根据主键删除实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool DeleteT(string id)
{
StringBuilder sql = new StringBuilder("delete from " + TableName + " where " + PrimaryKey + "='" + id + "'");
return dataModule.ExcuteSql(sql.ToString());
}
/// <summary>
/// 获取where 条件sql
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private Hashtable GetWhereConditionSQL(T entity)
{
StringBuilder whereCondition = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
whereCondition.Append(" " + property.Name + "=@" + property.Name + " and");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
if (property.Name == PrimaryKey)
{
break;
}
}
}
Hashtable ht = new Hashtable();
ht.Add("SQL", whereCondition.ToString().TrimEnd("and".ToArray()));
ht.Add("PAMS", paras.ToArray());
return ht;
}
/// <summary>
/// 设置实体属性值
/// </summary>
/// <param name="dt"></param>
/// <param name="entity"></param>
/// <returns></returns>
private T SetEntityValue(DataTable dt, T entity)
{
if (dt != null && dt.Rows.Count > 0)
{
foreach (PropertyInfo property in properties)
{
if (dt.Rows[0][property.Name] != DBNull.Value)
{
if (property.PropertyType == typeof(string))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToString(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(int?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt32(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(DateTime?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDateTime(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(long?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt64(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(double?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDouble(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(bool?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToBoolean(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(decimal?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDecimal(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(byte[]))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToByte(dt.Rows[0][property.Name]), null);
}
else
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToString(dt.Rows[0][property.Name]), null);
}
}
}
return entity;
}
else
{
return default(T);
}
}
}
/// DAO基类 实体名必须要与数据表字段名一致
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseDao<T> where T : new()
{
protected DataModule dataModule = new DataModule();
/// <summary>
/// 表名
/// </summary>
public virtual string TableName { get; set; }
/// <summary>
/// 主键ID
/// </summary>
public virtual string PrimaryKey { get; set; }
/// <summary>
/// 实体属性
/// </summary>
private PropertyInfo[] properties = null;
/// <summary>
/// 实体类型
/// </summary>
private readonly Type t = typeof(T);
public BaseDao()
{
t = typeof(T);
properties = t.GetProperties();
}
public BaseDao(string tableName, string primaryKey)
: this()
{
this.TableName = tableName;
this.PrimaryKey = primaryKey;
}
public int GetMaxID()
{
string sql = "select max(cast(" + PrimaryKey + " as decimal(18,0))) as MaxId from " + TableName;
DataTable dt = dataModule.GetDataTable(sql);
if (dt.Rows[0][0] == DBNull.Value)
{
return 1;
}
else
{
return Convert.ToInt32(dt.Rows[0][0]) + 1;
}
}
/// <summary>
/// 清除实体字段
/// </summary>
/// <param name="entity"></param>
public void ClearT(ref T entity)
{
entity = default(T);
entity = new T();
}
/// <summary>
/// 获取实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetT(string id)
{
string sql = "select * from " + TableName + " where " + PrimaryKey + "='" + id + "'";
DataTable dt = dataModule.GetDataTable(sql);
T entity = new T();
return SetEntityValue(dt, entity);
}
/// <summary>
/// 根据多个条件获取实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T GetT(T entity)
{
StringBuilder sql = new StringBuilder("select * from " + TableName + " where ");
Hashtable ht = GetWhereConditionSQL(entity);
string where = ht["SQL"] as string;
sql.Append(where);
SqlParameter[] paras = ht["PAMS"] as SqlParameter[];
DataTable dt = dataModule.GetDataTable(sql.ToString(), paras);
return SetEntityValue(dt, entity);
}
/// <summary>
/// 保存
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public bool InsertT(T entity)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
if (!string.IsNullOrEmpty(PrimaryKey) && t.GetProperty(PrimaryKey).GetValue(entity, null) == null)
{
if (t.GetProperty(PrimaryKey).PropertyType == typeof(string))
{
t.GetProperty(PrimaryKey).SetValue(entity, GetMaxID().ToString(), null);
}
else
{
t.GetProperty(PrimaryKey).SetValue(entity, GetMaxID(), null);
}
}
sql.Append(" Insert into " + TableName + " ( ");
StringBuilder insertFields = new StringBuilder("");
StringBuilder insertValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
insertFields.Append("" + property.Name + ",");
insertValues.Append("@" + property.Name + ",");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
}
}
sql.Append(insertFields.ToString().TrimEnd(','));
sql.Append(" ) VALUES ( ");
sql.Append(insertValues.ToString().TrimEnd(','));
sql.Append(")");
return dataModule.ExcuteSql(sql.ToString(), paras.ToArray());
}
/// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool UpdateT(T entity)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
sql.Append(" update " + TableName + " set ");
StringBuilder updateValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
updateValues.Append(property.Name + "=@" + property.Name + ",");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
}
else
{
updateValues.Append(property.Name + "=null,");
}
}
sql.Append(updateValues.ToString().TrimEnd(','));
sql.Append(" where " + PrimaryKey + "=@" + PrimaryKey);
return dataModule.ExcuteSql(sql.ToString(), paras.ToArray());
}
/// <summary>
/// 更新指定字段
/// </summary>
/// <param name="entity"></param>
/// <param name="field">实体属性名称</param>
/// <returns></returns>
public bool UpdateT(T entity, string field)
{
StringBuilder sql = new StringBuilder("");
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
}
sql.Append(" update " + TableName + " set ");
StringBuilder updateValues = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
updateValues.Append(field + "=@" + field + " ");
paras.Add(new SqlParameter("@" + field, t.GetProperty(field).GetValue(entity, null)));
sql.Append(updateValues.ToString());
sql.Append(" where " + PrimaryKey + "=@" + PrimaryKey);
paras.Add(new SqlParameter("@" + PrimaryKey,t.GetProperty(PrimaryKey).GetValue(entity, null)));
return dataModule.ExcuteSql(sql.ToString(),paras.ToArray());
}
/// <summary>
/// 根据多个字段删除实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool DeleteT(T entity)
{
StringBuilder sql = new StringBuilder("delete from " + TableName + " where ");
Hashtable ht = GetWhereConditionSQL(entity);
string where = ht["SQL"] as string;
sql.Append(where);
SqlParameter[] paras = ht["PAMS"] as SqlParameter[];
return dataModule.ExcuteSql(sql.ToString(), paras);
}
/// <summary>
/// 根据主键删除实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool DeleteT(string id)
{
StringBuilder sql = new StringBuilder("delete from " + TableName + " where " + PrimaryKey + "='" + id + "'");
return dataModule.ExcuteSql(sql.ToString());
}
/// <summary>
/// 获取where 条件sql
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private Hashtable GetWhereConditionSQL(T entity)
{
StringBuilder whereCondition = new StringBuilder("");
List<SqlParameter> paras = new List<SqlParameter>();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
whereCondition.Append(" " + property.Name + "=@" + property.Name + " and");
paras.Add(new SqlParameter("@" + property.Name, property.GetValue(entity, null)));
if (property.Name == PrimaryKey)
{
break;
}
}
}
Hashtable ht = new Hashtable();
ht.Add("SQL", whereCondition.ToString().TrimEnd("and".ToArray()));
ht.Add("PAMS", paras.ToArray());
return ht;
}
/// <summary>
/// 设置实体属性值
/// </summary>
/// <param name="dt"></param>
/// <param name="entity"></param>
/// <returns></returns>
private T SetEntityValue(DataTable dt, T entity)
{
if (dt != null && dt.Rows.Count > 0)
{
foreach (PropertyInfo property in properties)
{
if (dt.Rows[0][property.Name] != DBNull.Value)
{
if (property.PropertyType == typeof(string))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToString(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(int?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt32(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(DateTime?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDateTime(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(long?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt64(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(double?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDouble(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(bool?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToBoolean(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(decimal?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDecimal(dt.Rows[0][property.Name]), null);
}
else if (property.PropertyType == typeof(byte[]))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToByte(dt.Rows[0][property.Name]), null);
}
else
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToString(dt.Rows[0][property.Name]), null);
}
}
}
return entity;
}
else
{
return default(T);
}
}
}