winform中利用反射实现泛型数据访问对象基类(2)
在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);
}
} }
winform中利用反射实现泛型数据访问对象基类(2)的更多相关文章
- winform中利用反射实现泛型数据访问对象基类(1)
考虑到软件使用在客户端,同时想简化代码的实现,就写了一个泛型的数据访问对象基类,并不是特别健全,按道理应该参数化的方式实现insert和update,暂未使用参数化,抽时间改进. /// <su ...
- winform中利用反射实现泛型数据访问对象基类(3)
继续完善了几点代码 满足没有主键的情况下使用 并且完善实体字段反射设置value时的类型转换 /// <summary> /// DAO基类 实体名必须要与数据表字段名一致 /// < ...
- 利用反射和泛型把Model对象按行储存进数据库以及按行取出然后转换成Model 类实例 MVC网站通用配置项管理
利用反射和泛型把Model对象按行储存进数据库以及按行取出然后转换成Model 类实例 MVC网站通用配置项管理 2018-3-10 15:18 | 发布:Admin | 分类:代码库 | 评论: ...
- JAVAWEB基础模块开发顺序与数据访问对象实现类步骤
一.模块的开发的顺序 1. 定义数据表 2. 新建模型类 3. 新建"add.jsp" 4. 实现AddServlet中的doGet()方法 5. 定义Dao.Service接口 ...
- C#利用反射和泛型给不同对象赋值
/// <summary> /// 适用于初始化新实体 /// </summary> static public T RotationMapping<T, S>(S ...
- EntityFramework经典数据访问层基类——增删改查
namespace StudentSys.DAL { public class BaseService<T>:IDisposable where T:BaseEntity,new() { ...
- Java数据访问对象模式
数据访问对象模式或DAO模式用于将低级数据访问API或操作与高级业务服务分离. 以下是数据访问对象模式的参与者. 数据访问对象接口 - 此接口定义要对模型对象执行的标准操作. 数据访问对象具体类 - ...
- [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦
[.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦 本节导读:上篇文章简单介绍了.NET面向对象中一个重要的技术反射的基本应用,它可以让我们动态的调 ...
- DataTable转任意类型对象List数组-----工具通用类(利用反射和泛型)
public class ConvertHelper<T> where T : new() { /// <summary> /// 利用反射和泛型 /// </summa ...
随机推荐
- sdutoj 2604 Thrall’s Dream
http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2604 Thrall’s Dream Time ...
- [原创]java WEB学习笔记53:Struts2学习之路---前奏:使用 Filter 作为控制器的 MVC
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Java基础(53):内部类(转)
java中的内部类总结 内部类不是很好理解,但说白了其实也就是一个类中还包含着另外一个类 如同一个人是由大脑.肢体.器官等身体结果组成,而内部类相当于其中的某个器官之一,例如心脏:它也有自己的属性和行 ...
- Java基础(47):插入排序的Java封装(含原理,可运行,哨兵位的理解见VisualGo上面的动态分析)
直接插入排序(Straight Insertion Sorting)的基本思想:在要排序的一组数中,假设前面(n-1) [n>=2] 个数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使 ...
- ajax常用参数
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址.前台跳转到后台 请求参数:前台向后台传数据 回调函数:回调函数就是一个自定义的函数在发生特定的事件的时候调用来处理这个事件 ...
- 复习课程jdbc:使用配置文件properties进行连接数据库,数据库存取图片,批处理,时间戳,事物回滚等等
使用配置文件properties进行连接数据库 首先创建一个file自定义文件名,但是后缀名必须改为.properties(不分大小写):如config.properties: 然后双击config. ...
- 08---Net基础加强
资料管理器作业 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void F ...
- rails创建项目,部署,测试流程(rails5.0+ruby2.3.1)
rails new test_app --skip-test-unit 不生成默认的test,稍后用rspeccd test_app 修改Gemfile(大部分为自动生成) source 'https ...
- webform 文件上传(头像上传) 隐藏FileUpload
<div> <%-- 核心思想:把FileUpload设为relative,top:-200px;opacity: --%> <div id="localIma ...
- C++线性方程求解
介绍 程序SolveLinearEquations解决联立方程.该方案需要一个文本文件,其中包含输入和输出方程解决.这个项目是几年前我写在C#中http://www.codeproject.com/A ...