using Dapper;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using WIDESEA_Core.Const;
using WIDESEA_Core.DBManager;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Extensions;
using WIDESEA_Core.Utilities;
namespace WIDESEA_Core.Dapper
{
public class SqlDapper : ISqlDapper
{
private string _connectionString;
private IDbConnection _connection { get; set; }
public IDbConnection Connection
{
get
{
if (_connection == null || _connection.State == ConnectionState.Closed)
{
_connection = DBServerProvider.GetDbConnection(_connectionString);
}
return _connection;
}
}
public SqlDapper()
{
_connectionString = DBServerProvider.GetConnectionString();
}
///
/// string mySql = "Data Source=132.232.2.109;Database=mysql;User
/// ID=root;Password=mysql;pooling=true;CharSet=utf8;port=3306;sslmode=none";
/// this.conn = new MySql.Data.MySqlClient.MySqlConnection(mySql);
///
///
public SqlDapper(string connKeyName)
{
_connectionString = DBServerProvider.GetConnectionString(connKeyName);
}
private bool _transaction { get; set; }
///
/// 2020.06.15增加Dapper事务处理
///
///
public void BeginTransaction(Func action, Action error)
{
_transaction = true;
try
{
Connection.Open();
dbTransaction = Connection.BeginTransaction();
bool result = action(this);
if (result)
{
dbTransaction?.Commit();
}
else
{
dbTransaction?.Rollback();
}
}
catch (Exception ex)
{
dbTransaction?.Rollback();
error(ex);
}
finally
{
Connection?.Dispose();
dbTransaction?.Dispose();
_transaction = false;
}
}
///
/// var p = new object();
// p.Add("@a", 11);
//p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
//p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
// ///
///
///
///
///
///
public List QueryList(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false) where T : class
{
return Execute((conn, dbTransaction) =>
{
return conn.Query(cmd, param, dbTransaction, commandType: commandType ?? CommandType.Text).ToList();
}, beginTransaction);
}
public T QueryFirst(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false) where T : class
{
List list = QueryList(cmd, param, commandType: commandType ?? CommandType.Text, beginTransaction: beginTransaction).ToList();
return list.Count == 0 ? null : list[0];
}
public object ExecuteScalar(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false)
{
return Execute