winform中利用反射实现泛型数据访问对象基类(1)
考虑到软件使用在客户端,同时想简化代码的实现,就写了一个泛型的数据访问对象基类,并不是特别健全,按道理应该参数化的方式实现insert和update,暂未使用参数化,抽时间改进。
/// <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 string GetMaxID()
{
string sql = "select max(cast(" + PrimaryKey + " as int)) as MaxId from " + TableName;
DataTable dt = dataModule.GetDataTable(sql);
if (dt.Rows[][] == DBNull.Value)
{
return "";
}
else
{
return (Convert.ToInt64(dt.Rows[][]) + ).ToString();
}
} /// <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 ");
string where = GetWhereConditionSQL(entity);
sql.Append(where);
DataTable dt = dataModule.GetDataTable(sql.ToString());
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());
}
t.GetProperty(PrimaryKey).SetValue(entity, GetMaxID(), null);
sql.Append(" Insert into " + TableName + " ( ");
StringBuilder insertFields = new StringBuilder("");
StringBuilder insertValues = new StringBuilder("");
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
insertFields.Append("" + property.Name + ",");
if (property.PropertyType == typeof(string))
{
insertValues.Append("'" + property.GetValue(entity, null).ToString() + "',");
}
else if (property.PropertyType == typeof(DateTime?))
{
insertValues.Append("'" + Convert.ToDateTime(property.GetValue(entity, null)).ToString("yyyy-MM-dd HH:mm:ss") + "',");
}
else if (property.PropertyType == typeof(int?) || property.PropertyType == typeof(long?) || property.PropertyType == typeof(double?) || property.PropertyType == typeof(float?) || property.PropertyType == typeof(decimal?))
{
insertValues.Append("" + property.GetValue(entity, null).ToString() + ",");
}
else
{
insertValues.Append("'" + property.GetValue(entity, null).ToString() + "',");
}
} }
sql.Append(insertFields.ToString().TrimEnd(','));
sql.Append(" ) VALUES ( ");
sql.Append(insertValues.ToString().TrimEnd(','));
sql.Append(")"); return dataModule.ExcuteSql(sql.ToString());
} public bool UpdateT(T entity)
{
StringBuilder sql = new StringBuilder("");
//获取主键ID的值
string id = string.Empty;
if (t.GetProperty(PrimaryKey).GetValue(entity, null) != null)
{
id = t.GetProperty(PrimaryKey).GetValue(entity, null).ToString();
}
if (string.IsNullOrEmpty(TableName))
{
TableName = t.FullName.TrimStart((t.Namespace + ".").ToArray());
} sql.Append(" update " + TableName + " set ");
StringBuilder updateValues = new StringBuilder("");
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
if (property.PropertyType == typeof(string))
{
updateValues.Append(property.Name + "='" + property.GetValue(entity, null) + "',");
}
else if (property.PropertyType == typeof(DateTime?))
{
updateValues.Append(property.Name + "='" + Convert.ToDateTime(property.GetValue(entity, null)).ToString("yyyy-MM-dd HH:mm:ss") + "',");
}
else if (property.PropertyType == typeof(int?) || property.PropertyType == typeof(long?) || property.PropertyType == typeof(double?) || property.PropertyType == typeof(float?) || property.PropertyType == typeof(decimal?))
{
updateValues.Append(property.Name + "=" + property.GetValue(entity, null) + ",");
}
else
{
updateValues.Append(property.Name + "='" + property.GetValue(entity, null) + "',");
} }
else
{
updateValues.Append(property.Name + "=null,");
} }
sql.Append(updateValues.ToString().TrimEnd(','));
sql.Append(" where " + PrimaryKey + "=" + id); return dataModule.ExcuteSql(sql.ToString());
} /// <summary>
/// 根据多个字段删除实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool DeleteT(T entity)
{
StringBuilder sql = new StringBuilder("delete from " + TableName + " where ");
string where = GetWhereConditionSQL(entity);
sql.Append(where);
return dataModule.ExcuteSql(sql.ToString());
} /// <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 string GetWhereConditionSQL(T entity)
{
StringBuilder whereCondition = new StringBuilder("");
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) != null)
{
if (property.PropertyType == typeof(string))
{
whereCondition.Append(" " + property.Name + "='" + property.GetValue(entity, null) + "' and");
}
else if (property.PropertyType == typeof(DateTime?))
{
whereCondition.Append(" " + property.Name + "='" + Convert.ToDateTime(property.GetValue(entity, null)).ToString("yyyy-MM-dd HH:mm:ss") + "' and");
}
else if (property.PropertyType == typeof(int?) || property.PropertyType == typeof(long?) || property.PropertyType == typeof(double?) || property.PropertyType == typeof(float?) || property.PropertyType == typeof(decimal?))
{
whereCondition.Append(" " + property.Name + "=" + property.GetValue(entity, null) + " and");
}
else
{
whereCondition.Append(" " + property.Name + "='" + property.GetValue(entity, null) + "' and");
}
if (property.Name == PrimaryKey)
{
break;
}
} }
return whereCondition.ToString().TrimEnd("and".ToArray());
} /// <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 == typeof(string))
{
t.GetProperty(property.Name).SetValue(entity, dt.Rows[][property.Name], null);
}
else if (property.PropertyType == typeof(int?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt32(dt.Rows[][property.Name]), null);
}
else if (property.PropertyType == typeof(DateTime?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDateTime(dt.Rows[][property.Name]), null);
}
else if (property.PropertyType == typeof(long?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToInt64(dt.Rows[][property.Name]), null);
}
else if (property.PropertyType == typeof(double?))
{
t.GetProperty(property.Name).SetValue(entity, Convert.ToDouble(dt.Rows[][property.Name]), null);
}
else
{
t.GetProperty(property.Name).SetValue(entity, dt.Rows[][property.Name], null);
} }
}
return entity;
}
else
{
return default(T);
}
} }
如何使用,通过将表名和主键字段名传入进去,如果多个字段是主键的情况下,可以建一个主键列,然后将多个主键的列改为索引,因为任何一个表都可以创建出一个主键列,所以暂时不影响我使用
public BaseDao<TrafficEvent> EventDao = new BaseDao<TrafficEvent>("Sj_Event", "EventId");
UI层可以同过这种方式直接调用,目前可以暂时满足我的开发
eventBiz.EventDao.InsertT(trafficEvent)
eventBiz.EventDao.UpdateT(trafficEvent)
winform中利用反射实现泛型数据访问对象基类(1)的更多相关文章
- winform中利用反射实现泛型数据访问对象基类(3)
继续完善了几点代码 满足没有主键的情况下使用 并且完善实体字段反射设置value时的类型转换 /// <summary> /// DAO基类 实体名必须要与数据表字段名一致 /// < ...
- winform中利用反射实现泛型数据访问对象基类(2)
在1的基础上做了一点改进 参数化处理 看上去更简洁 无主键情况下 update 方法需要改进 insert delete没有问题 /// <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 ...
随机推荐
- Python学习总结19:类(一)
在Python中,可以通过class关键字定义自己的类,通过类私有方法“__init__”进行初始化.可以通过自定义的类对象类创建实例对象. class Student(object): count ...
- Java基础(33):StringBuilder的方法与应用实例(String相关类)
Java 中的 StringBuilder 类的常用方法 重要的事情说三遍: 在需要频繁对字符串进行修改操作时使用 StringBuilder 的效率比 String 要高 在需要频繁对字符串进行修改 ...
- B/S与C/S区别
B/S (Brower/Server)-->浏览器/服务器 程序完全部署在服务器上,用户通过浏览器访问应用程序,它是基于internet产物(在应用服务器中部署运行程序) c/s(Client/ ...
- JSon_零基础_005_将po(bean)对象集合List转换为JSon格式的对象字符串,返回给界面
将po(bean)对象集合List转换为JSon格式的对象字符串,返回给界面 导入jar包: 编写:po(bean)代码: package com.west.webcourse.po; /** * 第 ...
- paper 89:视频图像去模糊常用处理方法
随着“平安城市”的广泛建设,各大城市已经建有大量的视频监控系统,虽然监控系统己经广泛地存在于银行.商场.车站和交通路口等公共场所,但是在公安工作中,由于设备或者其他条件的限制,案情发生后的图像回放都存 ...
- DOM事件处理有三个阶段
DOM事件处理有三个阶段: 捕捉阶段(capture phase):从最上层元素,直到最下层(你点击的那个target)元素.路过的所有节点都可以捕捉到该事件. 命中阶段(target phase): ...
- JSP-02- 使用JSP实现输出
二. 使用JSP实现输出 JSP的页面构成: 静态内容.指令.表达式.Scriptlet.声明.动作.注释 Jsp脚本: 表达式.Scriptlet.声明 表达式: <%= 内容 %> ...
- 如何把一个java工程打成一个jar包(转载)
1.jar包有入口(即有main()函数) 选中要打包的工程--->右键选择Export---->java----->Runnable java file----->next- ...
- RMQ(非log2储存方法)
2016-03-31 RMQ 难度级别:B: 运行时间限制:1000ms: 运行空间限制:256000KB: 代码长度限制:2000000B 试题描述 长度为n的数列A,以及q个询问,每次询问一段区间 ...
- 详解Android AM命令
1.简介 在Android中,我们除了从界面上启动程序之外,还可以从命令行启动程序,如使用命令行工具am. am全称activity manager,是Android下非常实用命令,其代码在frame ...