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. 1.NetDh框架之数据库操作层--Dapper简单封装,可支持多库实例、多种数据库类型等(附源码和示例代码)

    1.NetDh框架开始的需求场景 需求场景: 1.之前公司有不同.net项目组,有的项目是用SqlServer做数据库,有的项目是用Oracle,后面也有可能会用到Mysql等,而且要考虑后续扩展成主 ...

  2. 分享一个dapper简单封装

    using System;using System.Data.Common;using System.Linq;using Dapper;using MySql.Data.MySqlClient; p ...

  3. .net core 中简单封装Dapper.Extensions 并使用sqlsuger自动生成实体类

    引言 由公司需要使用dapper  同时支持多数据库 又需要支持实体类 又需要支持sql 还需要支持事务 所以采用了 dapper + dapperExtensions  并配套 生成实体类小工具的方 ...

  4. .Net Framework下对Dapper二次封装迁移到.Net Core2.0遇到的问题以及对Dapper的封装介绍

    今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...

  5. Dapper的封装、二次封装、官方扩展包封装,以及ADO.NET原生封装

    前几天偶然看到了dapper,由于以前没有用过,只用过ef core,稍微看了一下,然后写了一些简单的可复用的封装. Dapper的用法比较接近ADO.NET所以性能也是比较快.所以我们先来看看使用A ...

  6. Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池

    前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...

  7. FMDB简单封装和使用

    工具:火狐浏览器+SQLite Manager插件 ; Xcode; FMDB库; 效果: 项目地址: https://github.com/sven713/PackFMDB 主要参考这两篇博客: 1 ...

  8. Android--Retrofit+RxJava的简单封装(三)

    1,继续接着上一篇的讲讲,话说如果像上一篇这样的话,那么我们每一次请求一个结构都要创建一堆的Retrofit对象,而且代码都是相同的,我们可以试试封装一下 先创建一个HttpMethods类,将Ret ...

  9. okhttp3 get post 简单封装

    最近打算在新项目中使用 okhttp3, 简单封装了一下异步 get post 因为 CallBack 也是在子线程中执行,所以用到了 Handler public class MyOkHttpCli ...

随机推荐

  1. 转:oracle常见重要视图-v$sql,v$sql_plan,v$sqltext,v$sqlarea,v$sql_plan_statistcs

    v$sql V$SQL中存储具体的SQL语句. 一条语句可以映射多个cursor,因为对象所指的cursor可以有不同用户(如例1).如果有多个cursor(子游标)存在,在V$SQLAREA为所有c ...

  2. KMP算法详解(转)

    转自http://www.matrix67.com/blog/archives/115 通常我们的方法是枚举从A串的什么位置起开始与B匹配,然后验证是否匹配.假如A串长度为n,B串长度为m,那么这种方 ...

  3. CodeIgniter框架隐藏index.php

    问题描述:使用CodeIgniter框架做项目时,在启用REWRITE的伪静态功能的时候,首页可以访问,但是访问其它页面的时候,就提示:“No input file specified.” 原因在于使 ...

  4. NetBeans配置Xdebug 远程调试PHP

    1.配置PHP 说明:xdebug.trace_output_dir和xdebug.profiler_output_dir需要增加权限 #chmod 755 /usr/xdebug-tmp xdebu ...

  5. Linux quota命令参数及用法详解---Linux磁盘配额限制设置和查看命令

    功能说明:显示磁盘已使用的空间与限制. 语 法:quota [-quvV][用户名称...] 或 quota [-gqvV][群组名称...] 补充说明:执行quota指令,可查询磁盘空间的限制,并得 ...

  6. seureCRT快捷键

    前言    secureCRT 是一个非常不错的终端软件,在嵌入式开发过程中经常使用到,所以了解一下其快捷键操作是非常有必要的,可以提高开发效率. 复制:[ctrl] + [shift] + c 粘贴 ...

  7. 优化深度神经网络(一) dropout 初始化

    Coursera吴恩达<优化深度神经网络>课程笔记(1)-- 深度学习的实用层面 1. Train/Dev/Test sets  训练集(Training sets).验证集(Develo ...

  8. Python 中的 is 和 == 编码和解码

    一   is   与   ==   区别 ==    比较            比较的是值 例如: a = 'alex' b = 'alex' print(a == b) #True a = 10 ...

  9. python3.3 MD5

    代码如下: # /usr/bin/python # -*- coding:utf-8 -*- import hashlib h=hashlib.md5() data = ' h.update(data ...

  10. 如何判定Unity已破解成功

    [如何判定Unity已破解成功] 点击菜单“Unity”->"About Unity...".在弹出的关于Unity的信息的对话框中,如果是已破解版本,在右下角会显示序列号.