继续完善了几点代码 满足没有主键的情况下使用 并且完善实体字段反射设置value时的类型转换

    /// <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 long GetMaxID()
{
string sql = "select max(cast(" + PrimaryKey + " as decimal(18,0))) as MaxId from " + TableName;
DataTable dt = dataModule.GetDataTable(sql);
if (dt.Rows[][] == DBNull.Value)
{
return ;
}
else
{
return Convert.ToInt64(dt.Rows[][]) + ;
}
} /// <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 if (t.GetProperty(PrimaryKey).PropertyType == typeof(int?) || t.GetProperty(PrimaryKey).PropertyType == typeof(int))
{
t.GetProperty(PrimaryKey).SetValue(entity, Convert.ToInt32(GetMaxID()), 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="conditions">指定的条件字段</param>
/// <returns></returns>
public bool UpdateT(T entity, params string[] conditions)
{
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 ");
StringBuilder whereValues = new StringBuilder("");
foreach (string condition in conditions)
{
whereValues.Append(condition + "=@" + condition + " and");
}
sql.Append(whereValues.ToString().TrimEnd("and".ToArray()));
return dataModule.ExcuteSql(sql.ToString(), paras.ToArray());
} /// <summary>
/// 更新指定字段
/// </summary>
/// <param name="entity"></param>
/// <param name="fields">需要更新的字段</param>
/// <returns></returns>
public bool UpdateFields(T entity, params string[] fields)
{
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 (string field in fields)
{
updateValues.Append(field + "=@" + field + ",");
paras.Add(new SqlParameter("@" + field, t.GetProperty(field).GetValue(entity, null)));
sql.Append(updateValues.ToString().TrimEnd(','));
}
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 > )
{
foreach (PropertyInfo property in properties)
{
if (dt.Rows[][property.Name] != DBNull.Value)
{
if (!property.PropertyType.IsGenericType)
{
t.GetProperty(property.Name).SetValue(entity, Convert.ChangeType(dt.Rows[][property.Name], property.PropertyType), null);
}
else
{
Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ChangeType(dt.Rows[][property.Name], Nullable.GetUnderlyingType(property.PropertyType)), null);
}
} //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?) || property.PropertyType == typeof(int))
//{
// t.GetProperty(property.Name).SetValue(entity, Convert.ToInt32(dt.Rows[0][property.Name]), null);
//}
//else if (property.PropertyType == typeof(DateTime?) || property.PropertyType == typeof(DateTime))
//{
// t.GetProperty(property.Name).SetValue(entity, Convert.ToDateTime(dt.Rows[0][property.Name]), null);
//}
//else if (property.PropertyType == typeof(long?) || property.PropertyType == typeof(long))
//{
// t.GetProperty(property.Name).SetValue(entity, Convert.ToInt64(dt.Rows[0][property.Name]), null);
//}
//else if (property.PropertyType == typeof(double?) || property.PropertyType == typeof(double))
//{
// t.GetProperty(property.Name).SetValue(entity, Convert.ToDouble(dt.Rows[0][property.Name]), null);
//}
//else if (property.PropertyType == typeof(bool?) || property.PropertyType == typeof(bool))
//{
// t.GetProperty(property.Name).SetValue(entity, Convert.ToBoolean(dt.Rows[0][property.Name]), null);
//}
//else if (property.PropertyType == typeof(decimal?) || 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);
}
} }

winform中利用反射实现泛型数据访问对象基类(3)的更多相关文章

  1. winform中利用反射实现泛型数据访问对象基类(1)

    考虑到软件使用在客户端,同时想简化代码的实现,就写了一个泛型的数据访问对象基类,并不是特别健全,按道理应该参数化的方式实现insert和update,暂未使用参数化,抽时间改进. /// <su ...

  2. winform中利用反射实现泛型数据访问对象基类(2)

    在1的基础上做了一点改进 参数化处理 看上去更简洁 无主键情况下 update 方法需要改进 insert delete没有问题  /// <summary>     /// DAO基类 ...

  3. 利用反射和泛型把Model对象按行储存进数据库以及按行取出然后转换成Model 类实例 MVC网站通用配置项管理

    利用反射和泛型把Model对象按行储存进数据库以及按行取出然后转换成Model 类实例 MVC网站通用配置项管理   2018-3-10 15:18 | 发布:Admin | 分类:代码库 | 评论: ...

  4. JAVAWEB基础模块开发顺序与数据访问对象实现类步骤

    一.模块的开发的顺序 1. 定义数据表 2. 新建模型类 3. 新建"add.jsp" 4. 实现AddServlet中的doGet()方法 5. 定义Dao.Service接口 ...

  5. C#利用反射和泛型给不同对象赋值

    /// <summary> /// 适用于初始化新实体 /// </summary> static public T RotationMapping<T, S>(S ...

  6. EntityFramework经典数据访问层基类——增删改查

    namespace StudentSys.DAL { public class BaseService<T>:IDisposable where T:BaseEntity,new() { ...

  7. Java数据访问对象模式

    数据访问对象模式或DAO模式用于将低级数据访问API或操作与高级业务服务分离. 以下是数据访问对象模式的参与者. 数据访问对象接口 - 此接口定义要对模型对象执行的标准操作. 数据访问对象具体类 - ...

  8. [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦

    [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦 本节导读:上篇文章简单介绍了.NET面向对象中一个重要的技术反射的基本应用,它可以让我们动态的调 ...

  9. DataTable转任意类型对象List数组-----工具通用类(利用反射和泛型)

    public class ConvertHelper<T> where T : new() { /// <summary> /// 利用反射和泛型 /// </summa ...

随机推荐

  1. Lintcode: Sort Letters by Case

    Given a string which contains only letters. Sort it by lower case first and upper case second. Note ...

  2. [转]WEB开发者必备的7个JavaScript函数

    我记得数年前,只要我们编写JavaScript,都必须用到几个常用的函数,比如,addEventListener 和 attachEvent,并不是为了很超前的技术和功能,只是一些基本的任务,原因是各 ...

  3. 从一简单程序看C语言内存分配

    int main13(){ char buf[20]="aaaa"; char buf2[] = "bbbb"; char *p1 = "111111 ...

  4. struts_20_对Action中所有方法、某一个方法进行输入校验(基于XML配置方式实现输入校验)

    第01步:导包 第02步:配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app ...

  5. 三层与MVC

    三层架构(3-tier architecture) 我们平时总是将三层架构与MVC混为一谈,殊不知它俩并不是一个概念.下面我来为大家揭晓我所知道的一些真相. 首先,它俩根本不是一个概念. 三层架构是一 ...

  6. [tp3.2.1]大D构建模型

    使用大(写字母)D方法: 如果,在默认到Home模块下面找不到UserModel模块,那么就会到Common模块下去找. 而如果此时在Common模块下还是找不到UserModel,那就会调用Mode ...

  7. 给Debian安装Xfce桌面

    1.sudo apt-get install xorg xdm xfce4   2.vi ~/.xinitrc,然后输入:exec xfce4,在终端输入startx命令后就能进入xfce4,或直接在 ...

  8. dataTabel转成dataview插入列后排序

    if (!string.IsNullOrEmpty(strQuyu) && !string.IsNullOrEmpty(strZuhao)) { string[] param = { ...

  9. OpenStack collectd的从零安装服务端

    安装collectd包操作同客户端相同,不在赘述 配置文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 ...

  10. Angularjs之基本概念梳理(一)

    1.Angularjs指令属性ng-app和ng-controller的理解 ng-app指令-标记了AngularJS脚本的作用域,在<html>中添加ng-app属性即说明整个< ...