介绍
dapper是一款轻量级的ORM Dapper 被称为 ORM 之王。
以下是 Dapper 的主要功能:
速度快,性能快。
更少的代码行。
对象映射器。
静态对象绑定。
动态对象绑定。
轻松处理 SQL 查询。
易于处理存储过程。
直接对 IDBConnection 类进行操作,该类提供平滑性并直接对数据库运行查询,而不是像我们在 EF 和 Web Page is Unavailable 中那样使用各种对像传递数据。
多查询支持。
支持存储过程。
批量数据插入功能。
Dapper 还允许基于多个输入获取多个数据。
为什么选择Dapper
Dapper 是第二快的 ORM
创建项目
1 新建 Dapper.DB 类库
1)接口:
public interface ISqlDapper
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entities"></param>
/// <param name="updateFileds">指定插入的字段</param>
/// <param name="beginTransaction">是否开启事务</param>
/// <returns></returns>
int Add<T>(T entity, Expression<Func<T, object>> updateFileds = null, bool beginTransaction = false);
}
引用:using Dapper;
2)通用方法
public class SqlDapper : ISqlDapper
{
private string _connectionString;
private int? commandTimeout = null;
private DbCurrentType _dbCurrentType;
public SqlDapper()
{
_connectionString = DBServerProvider.GetConnectionString();
}
public SqlDapper(string connKeyName, DbCurrentType dbCurrentType)
{
_dbCurrentType = dbCurrentType;
_connectionString = DBServerProvider.GetConnectionString(connKeyName);
}
public SqlDapper(string connKeyName)
{
_connectionString = DBServerProvider.GetConnectionString(connKeyName);
}
private bool _transaction { get; set; }
private IDbConnection _transactionConnection = null;
IDbTransaction dbTransaction = null;
private T Execute<T>(Func<IDbConnection, IDbTransaction, T> func, bool beginTransaction = false)
{
if (_transaction || dbTransaction != null)
{
return func(_transactionConnection, dbTransaction);
}
if (beginTransaction)
{
return ExecuteTransaction(func);
}
using (var connection = DBServerProvider.GetDbConnection(_connectionString, _dbCurrentType))
{
return func(connection, dbTransaction);
}
}
private T ExecuteTransaction<T>(Func<IDbConnection, IDbTransaction, T> func)
{
using (_transactionConnection = DBServerProvider.GetDbConnection(_connectionString, _dbCurrentType))
{
try
{
_transactionConnection.Open();
dbTransaction = _transactionConnection.BeginTransaction();
T reslutT = func(_transactionConnection, dbTransaction);
dbTransaction.Commit();
return reslutT;
}
catch (Exception ex)
{
dbTransaction?.Rollback();
throw ex;
}
finally
{
dbTransaction?.Dispose();
}
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="addFileds">指定插入的字段</param>
/// <param name="beginTransaction">是否开启事务</param>
/// <returns></returns>
public int Add<T>(T entity, Expression<Func<T, object>> addFileds = null, bool beginTransaction = false)
{
return AddRange<T>(new T[] { entity }, addFileds, beginTransaction);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entities"></param>
/// <param name="addFileds">指定插入的字段</param>
/// <param name="beginTransaction">是否开启事务</param>
/// <returns></returns>
public int AddRange<T>(IEnumerable<T> entities, Expression<Func<T, object>> addFileds = null, bool beginTransaction = true)
{
Type entityType = typeof(T);
var key = entityType.GetKeyProperty();
if (key == null)
{
throw new Exception("实体必须包括主键才能批量更新");
}
string[] columns;
//指定插入的字段
if (addFileds != null)
{
columns = addFileds.GetExpressionToArray();
}
else
{
var properties = entityType.GetGenericProperties();
if (key.PropertyType != typeof(Guid))
{
properties = properties.Where(x => x.Name != key.Name).ToArray();
}
columns = properties.Select(x => x.Name).ToArray();
}
//mysql批量写入待优化
string sql = $"insert into {entityType.GetEntityTableName()}({string.Join(",", columns)})" +
$"values(@{string.Join(",@", columns)});";
return Execute<int>((conn, dbTransaction) =>
{
//todo pgsql待实现
return conn.Execute(sql, (DBType.Name == DbCurrentType.MySql.ToString() || DBType.Name == DbCurrentType.PgSql.ToString()) ? entities.ToList() : null, dbTransaction);
}, beginTransaction);
}
/// <summary>
/// 开启事务
/// </summary>
/// <returns></returns>
public ISqlDapper BeginTrans()
{
_transaction = true;
_transactionConnection = DBServerProvider.GetDbConnection(_connectionString, _dbCurrentType);
_transactionConnection.Open();
dbTransaction = _transactionConnection.BeginTransaction();
return this;
}
/// <summary>
/// 提交
/// </summary>
public void Commit()
{
try
{
_transaction = false;
dbTransaction.Commit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_transactionConnection?.Dispose();
dbTransaction?.Dispose();
}
}
/// <summary>
/// 回滚
/// </summary>
public void Rollback()
{
try
{
_transaction = false;
dbTransaction?.Rollback();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_transactionConnection?.Dispose();
dbTransaction?.Dispose();
}
}
}
}
3)AppSetting 设置Connection 连接
public static class AppSetting
{
public static IConfiguration Configuration { get; private set; }
private static Connection _connection;
public static string DbConnectionString
{
get { return _connection.DbConnectionString; }
}
public static void Init(IServiceCollection services, IConfiguration configuration)
{
Configuration = configuration;
services.Configure<Connection>(configuration.GetSection("Connection"));
var provider = services.BuildServiceProvider();
_connection = provider.GetRequiredService<IOptions<Connection>>().Value;
DBType.Name = _connection.DBType;
}
}
public class Connection
{
public string DBType { get; set; }
public string DbConnectionString { get; set; }
}