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 ...
随机推荐
- java中求输入一个数,并计算其平方根~~~
总结:函数 Math.pow(x,0.5); package com.badu; import java.util.Scanner; // 输入一个数,并计算出平方根 public class AA ...
- 第八章 JVM内存管理
8.1 物理内存与虚拟内存 地址总线(连接处理器和RAM或处理器和寄存器的)的宽度影响了物理地址的索引范围,决定了处理器一次可以从寄存器或内存中获取多少个bit.同时决定了处理器最大的寻址空间,32位 ...
- 卷积神经网络之ResNet网络模型学习
Deep Residual Learning for Image Recognition 微软亚洲研究院的何凯明等人 论文地址 https://arxiv.org/pdf/1512.03385v1.p ...
- 使用模板创建第一个Web API项目
软件环境 vs 2015 update3 本节将通过例子讲述创建Web API 项目的方法 第一步,打开vs ,依次通过[文件]菜单,[新建][项目]命令,大致步骤如下图 : 第2步,在弹出对话框 ...
- WCF服务端返回:(413) Request Entity Too Large
出现这个原因我们应该都能猜测到,文件传出过大,超出了WCF默认范围,那么我们需要进行修改. 服务端和客户端都需要修改. 第一.客户端: <system.serviceModel> < ...
- PHP函数(四)-变量函数
变量函数 将声明的函数的函数名赋给一个变量,通过该变量来调用函数 <?php function Calculate($a,$b){ return $a + $b; } echo "计算 ...
- 虚拟机在 OpenStack 里没有共享存储条件下的在线迁移
虚拟机在 OpenStack 里没有共享存储条件下的在线迁移 本文尝试回答与 Live migration 相关的几个问题:Live migration 是什么?为什么要做 Live migratio ...
- windows重启mysql命令
开始->运行->cmd 停止:net stop mysql 启动:net start mysql 前提MYSQL已经安装为windows服务
- jquery添加和删除多个同名的input输入框
<script type="text/javascript"> function del(obj){ $(obj).parents("li").re ...
- pandas读写excel
import pandas as pd import numpy as np df = pd.read_csv("result.csv") # csv # df = pd.read ...