自己写的Dapper通用数据访问层
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Collections;
using System.Reflection;
using Knet.H5.Entity.Core; namespace Knet.H5.Toolkit.Data.Core
{
public class DapperDBase<T> where T : class,new()
{
public string TableName { get; set; }
public string Primarykey { get; set; }
public List<string> CoulmnsList { get; set; }
public DapperDBase()
{
var tablenameAttribute = (TableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TableAttribute));
Primarykey = tablenameAttribute.PrimaryKey;
TableName = tablenameAttribute.TableName;
CoulmnsList = GetEntityProperties(typeof(T));
} /// 得到web.config里配置项的数据库连接字符串。
private static readonly string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=ora9)));User Id=;Password=;"; private static DbConnection _db; private static readonly object objLocker = new object(); public static DbConnection DB
{
get
{
if (_db == null)
{
lock (objLocker)
{
if (_db == null)
{
Database Db = new OracleDatabase(connectionString);
DbConnection connection = Db.CreateConnection();
return connection;
}
}
}
return _db;
}
} /// <summary>
/// 根据ID获取model
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public T GetModelById(object Id)
{
string executeSql = @" SELECT " + string.Join(",", CoulmnsList) + " FROM " + this.TableName + " WHERE ID = :ID ";
var conditon = new { ID = Id };
return DB.Query<T>(executeSql, conditon).SingleOrDefault() ?? default(T);
} /// <summary>
/// 根据ID获取model
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public T GetModelById(object Id, params string[] selectCoumlns)
{
var selectFields = string.Empty;
if (selectCoumlns.Length > )
{
selectFields = string.Join<string>(",", selectCoumlns);
}
else
{
selectFields = string.Join(",", CoulmnsList);
}
string executeSql = @" SELECT " + selectFields + " FROM " + this.TableName + " WHERE " + this.Primarykey + " = :ID ";
var conditon = new { ID = Id };
return DB.Query<T>(executeSql, conditon).SingleOrDefault() ?? default(T);
} /// <summary>
/// 根据ID获取model
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public T GetModelByWhere(object whereObj)
{
var wherePro = whereObj.GetType().GetProperties();
var whereList= new List<string>();
foreach (var item in wherePro)
{
if (item.GetValue(whereObj) == null) continue;
whereList.Add(string.Format("{0}=:{0}", item.Name));
}
string executeSql = @" SELECT " + string.Join(",", CoulmnsList) + " FROM " + this.TableName;
if (whereList.Count > )
{
executeSql += " WHERE " + string.Join(" AND ", whereList);
}
return DB.Query<T>(executeSql, whereObj).SingleOrDefault() ?? default(T);
} /// <summary>
/// 获取列表
/// </summary>
/// <param name="whereStr">只能使用且的关系,且属于该model内的字段</param>
/// <param name="order">排序字段 create_date desc</param>
/// <returns></returns>
public List<T> GetList(object whereObj = null, string order = null)
{
var whereList = new List<string>();
if (whereObj != null)
{
var wherePro = whereObj.GetType().GetProperties();
foreach (var item in wherePro)
{
if (item.GetValue(whereObj) == null) continue;
whereList.Add(string.Format("{0}=:{0}", item.Name));
}
}
string executeSql = @" SELECT " + string.Join(",", CoulmnsList) + " FROM " + this.TableName;
if (whereList.Count > )
{
executeSql += " WHERE " + string.Join(" and ", whereList);
}
if (!string.IsNullOrEmpty(order))
{
executeSql += " ORDER BY " + order;
}
return DB.Query<T>(executeSql, whereObj).ToList();
} /// <summary>
/// 获取列表
/// </summary>
/// <param name="whereStr">只能使用且的关系,且属于该model内的字段</param>
/// <param name="order">排序字段 create_date desc</param>
/// <returns></returns>
public List<T> GetList(string whereStr = null, string order = null)
{
string executeSql = @" SELECT " + string.Join(",", CoulmnsList) + " FROM " + this.TableName;
if (!string.IsNullOrEmpty(whereStr))
{
executeSql += " where " + whereStr;
}
if (!string.IsNullOrEmpty(order))
{
executeSql += "order by " + order;
}
return DB.Query<T>(executeSql, whereStr).ToList();
} /// <summary>
/// 获取全部字段
/// </summary>
/// <param name="order">排序</param>
/// <returns></returns>
public List<T> GetAllList(string order = null)
{
string executeSql = @" SELECT " + string.Join(",", CoulmnsList) + " FROM " + this.TableName;
if (!string.IsNullOrEmpty(order))
{
executeSql += " ORDER BY " + order;
}
return DB.Query<T>(executeSql).ToList();
} /// <summary>
/// 插入
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public int Add(T model)
{
string executeSql = @" INSERT INTO " + this.TableName + " (" + string.Join(",", CoulmnsList) + " ) VALUES (" + string.Join(",:", CoulmnsList).Insert(, ":") + ") ";
return DB.Execute(executeSql, model);
} /// <summary>
/// 更新
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(T model)
{
var wherePro = model.GetType().GetProperties();
var whereSql = new List<string>();
foreach (var item in wherePro)
{
//if (item.GetValue(model) == null) continue;
whereSql.Add(string.Format("{0}=:{0}", item.Name));
}
string executeSql = @" UPDATE " + this.TableName + " SET " + string.Join(",", whereSql) + " WHERE " + this.Primarykey + "=:" + Primarykey;
return DB.Execute(executeSql, model) > ;
} /// <summary>
/// 根据条件更新指定的字段
/// </summary>
/// <param name="updateCoumlns"></param>
/// <param name="whereStr"></param>
/// <returns></returns>
public bool Update(object updateCoumlns, string whereStr)
{
var wherePro = updateCoumlns.GetType().GetProperties();
var whereSql = new List<string>();
foreach (var item in wherePro)
{
if (item.GetValue(updateCoumlns) == null) continue;
whereSql.Add(string.Format("{0}=:{0}", item.Name));
}
string executeSql = @" UPDATE " + this.TableName + " SET " + string.Join(",", whereSql);
if (!string.IsNullOrEmpty(whereStr))
{
executeSql += " WHERE " + whereStr;
}
return DB.Execute(executeSql, updateCoumlns) > ;
} //public bool Update(string[] fields,string value) /// <summary>
/// 获取分页数据
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="selectFields">查询的字段</param>
/// <param name="whereObj"></param>
/// <param name="order"></param>
/// <returns></returns>
public PagedList<T> GetPagerList(int pageIndex, int pageSize, string[] selectFields = null, object whereObj = null, string order = null)
{
var whereList = new List<string>();
if (whereObj != null)
{
var wherePro = whereObj.GetType().GetProperties();
foreach (var item in wherePro)
{
if (item.GetValue(whereObj) == null) continue;
whereList.Add(string.Format("{0}=:{0}", item.Name));
}
}
string orderSql = string.Empty, whereSql = string.Empty, fields = " row_.*";
if (!string.IsNullOrEmpty(order))
{
orderSql = " ORDER BY " + order;
}
if (whereList.Count > )
{
whereSql = " WHERE " + string.Join(" and ", whereList);
}
if (selectFields != null && selectFields.Length > )
{
fields = string.Join(",", selectFields);
}
string executeSql = @" SELECT COUNT(0) FROM " + this.TableName + whereSql;
int totalCount = DB.Query<int>(executeSql, whereObj).SingleOrDefault();
string pagerSql = "SELECT * FROM ( SELECT " + fields + ", rownum rownum_ from ( SELECT * FROM " + this.TableName + whereSql + orderSql + ") row_ where rownum <= " + pageIndex * pageSize + ") where rownum_ >" + (pageIndex - ) * pageSize + "";
var source = DB.Query<T>(pagerSql, whereObj).ToList();
return new PagedList<T>(source, pageIndex, pageSize, totalCount);
} /// <summary>
/// 删除数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool Delete(object id)
{
string executeSql = @" DELETE FROM " + this.TableName + " WHERE " + this.Primarykey + " = :ID";
var conditon = new { ID = id };
return DB.Execute(executeSql, conditon) > ;
} #region 直接执行sql /// <summary>
/// 执行sql语句,参数都以带入的形式
/// </summary>
/// <param name="executeSql"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool Update(string executeSql, object value)
{
return DB.Execute(executeSql, value) > ;
} /// <summary>
/// 执行sql语句,参数都以带入的形式
/// </summary>
/// <param name="executeSql"></param>
/// <param name="value"></param>
/// <returns></returns>
public int Add(string executeSql, object value)
{
return DB.Execute(executeSql, value);
} /// <summary>
/// 执行SQL获取table
/// </summary>
/// <param name="executeSql"></param>
/// <returns></returns>
public DataTable GetTable(string executeSql)
{
return DB.Query<DataTable>(executeSql).SingleOrDefault();
} /// <summary>
/// 执行SQL获取LIST
/// </summary>
/// <param name="executeSql"></param>
/// <returns></returns>
public List<T> GetList(string executeSql)
{
return DB.Query<T>(executeSql).ToList();
}
#endregion /// <summary>
/// 对datatable进行分页
/// </summary>
/// <param name="dt"></param>
/// <param name="PageIndex"></param>
/// <param name="PageSize"></param>
/// <returns></returns>
public DataTable SplitDataTable(DataTable dt, int PageIndex, int PageSize)
{
if (PageIndex == )
return dt;
DataTable newdt = dt.Clone();
//newdt.Clear();
int rowbegin = (PageIndex - ) * PageSize;
int rowend = PageIndex * PageSize; if (rowbegin >= dt.Rows.Count)
return newdt; if (rowend > dt.Rows.Count)
rowend = dt.Rows.Count;
for (int i = rowbegin; i <= rowend - ; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
} return newdt;
} /// <summary>
/// 获取实体所有属性名称
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private List<string> GetEntityProperties(Type type)
{
var list = new List<string>();
PropertyInfo[] properties = type.GetProperties();
foreach (var pro in properties)
{
var fieldsAttribute = new FieldsAttribute();
var attrmodel = pro.GetCustomAttributes<FieldsAttribute>(true).FirstOrDefault();
if (attrmodel != null )
{//controller上有标记
fieldsAttribute = attrmodel as FieldsAttribute;
}
if (!fieldsAttribute.IsSourceFields) continue;
// if ()
list.Add(pro.Name);
}
return list;
}
}
}
自己写的Dapper通用数据访问层的更多相关文章
- ClownFish:比手写代码还快的通用数据访问层
http://www.cnblogs.com/fish-li/archive/2012/07/17/ClownFish.html 阅读目录 开始 ClownFish是什么? 比手写代码还快的执行速度 ...
- 【原创】打造基于Dapper的数据访问层
[原创]打造基于Dapper的数据访问层 前言 闲来无事,花几天功夫将之前项目里用到的一个数据访问层整理了出来.实现单个实体的增删改查,可执行存储过程,可输出返回参数,查询结果集可根据实际情况返回 ...
- 基于Spring4+Hibernate4的通用数据访问层+业务逻辑层(Dao层+Service层)设计与实现!
基于泛型的依赖注入.当我们的项目中有很多的Model时,相应的Dao(DaoImpl),Service(ServiceImpl)也会增多. 而我们对这些Model的操作很多都是类似的,下面是我举出的一 ...
- 1.1 DAL数据访问层
分布式(Distributed)数据访问层(Data Access Layer),简称DAL,是利用MySQL Proxy.Memcached.集群等技术优点而构建的一个架构系统.主要目的是解决高并发 ...
- 企业级应用架构(三)三层架构之数据访问层的改进以及测试DOM的发布
在上一篇我们在宏观概要上对DAL层进行了封装与抽象.我们的目的主要有两个:第一,解除BLL层对DAL层的依赖,这一点我们通过定义接口做到了:第二,使我们的DAL层能够支持一切数据访问技术,如Ado.n ...
- 数据访问层的改进以及测试DOM的发布
数据访问层的改进以及测试DOM的发布 在上一篇我们在宏观概要上对DAL层进行了封装与抽象.我们的目的主要有两个:第一,解除BLL层对DAL层的依赖,这一点我们通过定义接口做到了:第二,使我们的DAL层 ...
- 数据访问层 (DAO)
数据持久化 持久化:将程序中的数据在瞬间状态下和持久状态间转换的机制(JDBC) 主要持久化操作:保存.删除.读取.和查找. 采用面向接口编程,可以降低代码间的耦合性,提高代码的可扩展性和可维护性. ...
- 同时支持EF+Dapper的混合仓储,助你快速搭建数据访问层
背景 17年开始,公司开始向DotNet Core转型,面对ORM工具的选型,当时围绕Dapper和EF发生了激烈的讨论.项目团队更加关注快速交付,他们主张使用EF这种能快速开发的ORM工具:而在线业 ...
- 项目架构开发:数据访问层之Repository
接上文 项目架构开发:数据访问层之Logger 本章我们继续IRepository开发,这个仓储与领域模式里边的仓储有区别,更像一个工具类,也就是有些园友说的“伪仓储”, 这个仓储只实现单表的CURD ...
随机推荐
- spm使用之三spm应用实例
spm 的init实际上是调用了grunt这个工具来实现一些交互式的提问和数据的获取. 看看npm就知道, npm有个命令叫init, 就是一样的交互式提问获取你要创建的nodejs的模块信息. sp ...
- java 上下文切换
上下文概念 在高性能编程时,经常接触到多线程. 起初我们的理解是, 多个线程并行地执行总比单个线程要快, 就像多个人一起干活总比一个人干要快. 然而实际情况是, 多线程之间需要竞争IO设备, 或者竞争 ...
- C++ Unicode SBCS 函数对照表,以备日后查阅(很全)
C++ Unicode SBCS 函数对照表,以备日后查阅 Generic SBCS UNICODE TCHAR char wchar_t _TEOF EOF WEOF _TINT int wint_ ...
- Spring MVC 解读——<context:component-scan/>
转自:http://my.oschina.net/HeliosFly/blog/203149 作者:GoodLoser. Spring MVC 解读---<context:component-s ...
- openwrt使用3G上网卡
尊敬的大大.感谢你抽空指导我 我的设备是db120 mu350 和广东无限卡 版本是OpenWrt Backfire 10.03.336 DIY full 一. 没有安装到kmod-us ...
- scrollView的用法
- (void)viewDidLoad { [super viewDidLoad]; scrollView = [[UIScrollView alloc] initWith ...
- JavaScript高级程序设计10.pdf
String类型有几种操作字符串的方法 concat()方法拼接任意多个字符串,不修改原字符串 var stringValue=“hello ”; var result=stringValue.con ...
- udev:renamed network interface eth0 to eth1
删除/etc/udev/rules.d/70-persistent-net.rules这个文件,重启
- 使用python实现最优化问题
最优化问题 1.无约束的最优化问题 所谓的无约束优化问题指的是一个优化问题的寻优可行集合是目标函数自变量的定义域,即没有外部的限制条件.例如,求解优化问题 [ \begin{array}{rl} \t ...
- 《算法问题实战策略》——chaper9——动态规划法技巧
Q1: 数字游戏: 两个人(A.B)用n个整数排成的一排棋盘玩游戏,游戏从A开始,每个人有如下操作: (1) 拿走棋盘最右侧或者最左侧的棋子,被拿走的数字从棋盘中抹掉. (2) 棋盘中还剩 ...