Dapper 简单封装
using System;
using System.Collections.Generic;
using System.Text;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using common.core.config;
using Npoi.Core.SS.Formula.Functions; namespace common.core.sqlserver
{
public class BaseService<TService, TEntity> where TService : BaseService<TService, TEntity>, new()
{
/// <summary>
/// 默认实例
/// </summary>
/// <returns>服务实例</returns>
public static TService Instance() => new TService(); /// <summary>
/// 插入多个
/// </summary>
/// <param name="listModel"></param>
public virtual int InsertMany(List<TEntity> listModel)
{
if (listModel == null || listModel.Count <= )
{
throw new Exception("插入数据不可为空");
}
TEntity model = listModel.FirstOrDefault();
var ps = model.GetType().GetProperties();
List<string> @colms = new List<string>();
List<string> @params = new List<string>(); foreach (var p in ps)
{
if (p.CustomAttributes.All(x => x.AttributeType != typeof(PrimaryKeyAttribute)) && p.CustomAttributes.All(x => x.AttributeType != typeof(DBIgnoreAttribute)))
{
@colms.Add(string.Format("[{0}]", p.Name));
@params.Add(string.Format("@{0}", p.Name));
}
}
var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", typeof(TEntity).Name, string.Join(", ", @colms), string.Join(", ", @params));
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
IDbTransaction transaction = _conn.BeginTransaction();
return _conn.Execute(sql, listModel, transaction, null, null);
} } /// <summary>
/// 插入一个
/// </summary>
/// <param name="model"></param>
public virtual int InsertOne(TEntity model)
{
if (model == null)
{
throw new Exception("插入数据不可为空");
}
var ps = model.GetType().GetProperties();
List<string> @colms = new List<string>();
List<string> @params = new List<string>(); foreach (var p in ps)
{
if (p.CustomAttributes.All(x => x.AttributeType != typeof(PrimaryKeyAttribute)) && p.CustomAttributes.All(x => x.AttributeType != typeof(DBIgnoreAttribute)))
{
@colms.Add(string.Format("[{0}]", p.Name));
@params.Add(string.Format("@{0}", p.Name));
}
}
var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", typeof(TEntity).Name, string.Join(", ", @colms), string.Join(", ", @params));
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(sql, model, null, null, null);
}
} /// <summary>
/// 查询一个
/// </summary>
/// <param name="whereProperties"></param>
/// <returns></returns>
public virtual TEntity GetOne(object whereProperties)
{
string where = "";
var listPropert = whereProperties.GetType().GetProperties();
if (listPropert.Length > )
{
where += " where ";
listPropert.ToList().ForEach(e =>
{
where += $" {e.Name} = @{e.Name} and";
});
}
where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
//返回单条信息
string query = $"SELECT * FROM { typeof(TEntity).Name}{where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.QuerySingleOrDefault<TEntity>(query, whereProperties);
}
} /// <summary>
/// 查询一个
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual TEntity GetOne(string where)
{
if (!string.IsNullOrEmpty(where))
{
where = $" where 1=1 and {where}";
}
//返回单条信息
string query = $"SELECT * FROM { typeof(TEntity).Name} {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.QuerySingleOrDefault<TEntity>(query);
}
} /// <summary>
/// 查询多个
/// </summary>
/// <param name="whereProperties"></param>
/// <returns></returns>
public virtual List<TEntity> GetMany(object whereProperties)
{
string where = "";
var listPropert = whereProperties.GetType().GetProperties();
if (listPropert.Length > )
{
where += " where ";
listPropert.ToList().ForEach(e =>
{
where += $" {e.Name} = @{e.Name} and";
});
}
where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
string query = $"SELECT * FROM { typeof(TEntity).Name}{where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Query<TEntity>(query, whereProperties)?.ToList();
}
} /// <summary>
/// 查询多个
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual List<TEntity> GetMany(string where)
{
if (!string.IsNullOrEmpty(where))
{
where = $" where 1=1 and {where}";
}
string query = $"SELECT * FROM { typeof(TEntity).Name} {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Query<TEntity>(query)?.ToList();
}
} /// <summary>
/// 是否存在
/// </summary>
/// <param name="whereProperties"></param>
/// <returns></returns>
public virtual bool Exists(object whereProperties)
{
return GetMany(whereProperties).Count > ;
} /// <summary>
/// 是否存在
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual bool Exists(string where)
{
return GetMany(where).Count > ;
} /// <summary>
/// 删除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual int DeleteById(TEntity entity)
{
if (entity == null)
{
throw new Exception("删除内容不可为空");
}
string where = "";
var listPropert = entity.GetType().GetProperties();
if (listPropert.Length > )
{
listPropert.ToList().ForEach(p =>
{
var primaryKey = p.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(PrimaryKeyAttribute));
if (primaryKey != null)
{
where += $" {p.Name} = @{p.Name} and";
}
});
} where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
if (string.IsNullOrEmpty(where))
{
throw new Exception("未找到Id");
}
string query = $"DELETE FROM { typeof(TEntity).Name} where {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(query, entity);
}
} /// <summary>
/// 删除
/// </summary>
/// <param name="whereProperties"></param>
/// <returns></returns>
public virtual int Delete(object whereProperties)
{
string where = "";
var listPropert = whereProperties.GetType().GetProperties();
if (listPropert.Length > )
{
listPropert.ToList().ForEach(e =>
{
where += $"{e.Name} = @{e.Name} and";
});
}
where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
if (string.IsNullOrEmpty(where))
{
throw new Exception("条件不可为空");
}
string query = $"DELETE FROM { typeof(TEntity).Name} where {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(query, whereProperties);
}
} /// <summary>
/// 删除
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual int Delete(string where)
{
if (string.IsNullOrEmpty(where))
{
throw new Exception("条件不可为空");
}
string query = $"DELETE FROM { typeof(TEntity).Name} where {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(query);
}
} /// <summary>
/// 根据Id更新
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual int UpdateById(TEntity entity)
{
if (entity == null)
{
throw new Exception("更新内容不可为空");
}
string where = "";
var listPropert = entity.GetType().GetProperties();
if (listPropert.Length > )
{
listPropert.ToList().ForEach(p =>
{
var primaryKey = p.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(PrimaryKeyAttribute));
if (primaryKey!=null)
{
where += $" {p.Name} = @{p.Name} and";
}
});
} where=where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
if (string.IsNullOrEmpty(where))
{
throw new Exception("未找到Id");
} string update = "";
var listPropertUpdate = entity.GetType().GetProperties();
if (listPropertUpdate.Length > )
{
update += "";
listPropertUpdate.ToList().ForEach(e =>
{
if (e.CustomAttributes.All(x => x.AttributeType != typeof(PrimaryKeyAttribute)) && e.CustomAttributes.All(x => x.AttributeType != typeof(DBIgnoreAttribute)))
{
update += $"{e.Name} = @{e.Name} ,";
}
});
}
update = update.TrimEnd(',');
if (string.IsNullOrEmpty(update))
{
throw new Exception("无更新内容");
}
string query = $"update { typeof(TEntity).Name} set {update} where {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(query, entity);
} } /// <summary>
/// 根据条件更新
/// </summary>
/// <param name="updateProperty"></param>
/// <param name="where"></param>
/// <returns></returns>
public virtual int Update(object updateProperty, string where)
{
if (string.IsNullOrEmpty(where))
{
throw new Exception("需输入条件");
}
string update = "";
var listPropertUpdate = updateProperty.GetType().GetProperties();
if (listPropertUpdate.Length > )
{
update += "";
listPropertUpdate.ToList().ForEach(e =>
{
update += $"{e.Name} = @{e.Name} ,";
});
}
update = update.TrimEnd(',');
if (string.IsNullOrEmpty(update))
{
throw new Exception("无更新内容");
}
string query = $"update { typeof(TEntity).Name} set {update} where {where}";
using (var _conn = new SqlConnection(CommonConfigUtil.GlobalConfigExtend.SqlServer.Url))
{
return _conn.Execute(query, updateProperty);
} }
}
}
Dapper 简单封装的更多相关文章
- 1.NetDh框架之数据库操作层--Dapper简单封装,可支持多库实例、多种数据库类型等(附源码和示例代码)
1.NetDh框架开始的需求场景 需求场景: 1.之前公司有不同.net项目组,有的项目是用SqlServer做数据库,有的项目是用Oracle,后面也有可能会用到Mysql等,而且要考虑后续扩展成主 ...
- 分享一个dapper简单封装
using System;using System.Data.Common;using System.Linq;using Dapper;using MySql.Data.MySqlClient; p ...
- .net core 中简单封装Dapper.Extensions 并使用sqlsuger自动生成实体类
引言 由公司需要使用dapper 同时支持多数据库 又需要支持实体类 又需要支持sql 还需要支持事务 所以采用了 dapper + dapperExtensions 并配套 生成实体类小工具的方 ...
- .Net Framework下对Dapper二次封装迁移到.Net Core2.0遇到的问题以及对Dapper的封装介绍
今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...
- Dapper的封装、二次封装、官方扩展包封装,以及ADO.NET原生封装
前几天偶然看到了dapper,由于以前没有用过,只用过ef core,稍微看了一下,然后写了一些简单的可复用的封装. Dapper的用法比较接近ADO.NET所以性能也是比较快.所以我们先来看看使用A ...
- Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池
前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...
- FMDB简单封装和使用
工具:火狐浏览器+SQLite Manager插件 ; Xcode; FMDB库; 效果: 项目地址: https://github.com/sven713/PackFMDB 主要参考这两篇博客: 1 ...
- Android--Retrofit+RxJava的简单封装(三)
1,继续接着上一篇的讲讲,话说如果像上一篇这样的话,那么我们每一次请求一个结构都要创建一堆的Retrofit对象,而且代码都是相同的,我们可以试试封装一下 先创建一个HttpMethods类,将Ret ...
- okhttp3 get post 简单封装
最近打算在新项目中使用 okhttp3, 简单封装了一下异步 get post 因为 CallBack 也是在子线程中执行,所以用到了 Handler public class MyOkHttpCli ...
随机推荐
- HDU 1878 欧拉回路(无向图的欧拉回路)
欧拉回路 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- PHP实现日志写入log.txt
引言:有时候调试,看不到效果,需要通过写入文件来实现. 案例: <?php $myfile = fopen("log.txt", "a+") or die ...
- PL/SQL 训练02--集合数组
1. 请列举关联数组.嵌套表.VARRAY三种集合类型的区别区别:1 关联数组只能在plsql中使用,嵌套表,varray可用于sql中,数据库表中的列2 嵌套表,varray必须在使用的时候初始化, ...
- ndarray的创建与数据类型
ndarray 多维数组(N Dimension Array) NumPy数组是一个多维的数组对象(矩阵),称为ndarray,具有矢量算术运算能力和复杂的广播能力,并具有执行速度快和节省空间的特点. ...
- SqlServer——常见问题汇总
1.存储过程手动执行正常,应用程序高并发允许时,数据成倍数增加 通常此类问题是由于存储过程中使用了永久表作为中间表,用以存储临时数据.当高并发时,比如同时执行3次,则同时往中间表中插入3倍的数据,得到 ...
- RT2870移植到s3c2416后续验证无线…
我的无线网卡显示的事ra0,所以把下面的wlan0换成ra0即可:视自己的情况而定 1. 打开无线网卡电源 iwconfig wlan0 txpower on 2. 列出区域内的无线网络 iwlist ...
- python3 破解 geetest(极验)的滑块验证码
Kernel_wu 快速学习的实践者 python3 破解 geetest(极验)的滑块验证码 from selenium import webdriver from selenium.webdriv ...
- Docker学习笔记_安装和使用Zookeeper
一.准备 1.宿主机OS:Win10 64位 2.虚拟机OS:Ubuntu18.04 3.账号:docker 二.安装 1.搜索镜像 ...
- Free GIS Software
Refer to There are lots of free gis software listed in the website: http://www.freegis.org/ http://w ...
- c语言实践 统计输入的一串正整数里面奇数和偶数的个数
怎么考虑这个问题. 首先先确定肯定是需要一个变量保存输入的数据的,我们叫它input,最后结果要的是个数,所以需要另外两个变量来保存奇数的个数和偶数的个数. int input int countJ ...