Commit efa08ef5 authored by 罗显健's avatar 罗显健
Browse files

数据访问测试类项目

parent c76caf61
......@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tools", "Tools\Tools.csproj
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ftt.PatchPack", "Ftt.PatchPack\Ftt.PatchPack.csproj", "{42E384C1-CC13-494D-90E2-33C399E13F07}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{1447F8DF-E552-40DD-8F02-B55D75FBC77A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -55,6 +57,18 @@ Global
{42E384C1-CC13-494D-90E2-33C399E13F07}.Release|x64.Build.0 = Release|Any CPU
{42E384C1-CC13-494D-90E2-33C399E13F07}.Release|x86.ActiveCfg = Release|Any CPU
{42E384C1-CC13-494D-90E2-33C399E13F07}.Release|x86.Build.0 = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|x64.ActiveCfg = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|x64.Build.0 = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|x86.ActiveCfg = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Debug|x86.Build.0 = Debug|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|Any CPU.Build.0 = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|x64.ActiveCfg = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|x64.Build.0 = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|x86.ActiveCfg = Release|Any CPU
{1447F8DF-E552-40DD-8F02-B55D75FBC77A}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>
using Dapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test.DBO
{
/// <summary>
/// Dapper Dbo.
/// 更换不同数据库,只需修改 NewConn <see cref="NewConn"/> 以及少量代码 <see cref="GetDataSet"/> <see cref="GetDataTable"/>
/// </summary>
public class DbDapper : IDisposable
{
public static bool DEBUG_MODE = false;
private readonly string connectionString;
private System.Data.IDbConnection conn;
/// <summary>
/// 平台用、企业相关操作禁止使用。
/// </summary>
/// <param name="dbConnectionString"></param>
public DbDapper(string dbConnectionString)
{
connectionString = dbConnectionString;
}
public IDbConnection NewConn()
{
// return new NpgsqlConnection(connectionString);
return new SqlConnection(connectionString);
}
/// <summary>
/// 在委托里执行一堆事务
/// 委托成功执行会自动提交事件,失败会自动回滚.
/// 注意:不要在这个委托里调用 带 Async的异步方法,可能会造成问题:BeginExecuteNonQuery requires an open and available Connection. The connection's current state is open
/// </summary>
/// <param name="action"></param>
public void Trans(Action<IDbConnection, IDbTransaction> action)
{
using (var conn = NewConn())
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
action(conn, trans);
trans.Commit();
}
catch (Exception)
{
trans.Rollback();
throw;
}
}
conn.Close();
}
}
public T ExecuteScalar<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return conn.ExecuteScalar<T>(commandText, paras, commandType: CommandType.Text);
}
}
public async Task<T> ExecuteScalarAsync<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return await conn.ExecuteScalarAsync<T>(commandText, paras, commandType: CommandType.Text);
}
}
public async Task<T> QueryFirstAsync<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return await conn.QueryFirstAsync<T>(commandText, paras, commandType: CommandType.Text);
}
}
public T QueryFirst<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return conn.QueryFirst<T>(commandText, paras, commandType: CommandType.Text);
}
}
public T QueryFirstOrDefault<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return conn.QueryFirstOrDefault<T>(commandText, paras, commandType: CommandType.Text);
}
}
public async Task<T> QueryFirstOrDefaultAsync<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return await conn.QueryFirstOrDefaultAsync<T>(commandText, paras, commandType: CommandType.Text);
}
}
public void Execute(string commandText, object paras = null)
{
using (var conn = NewConn())
{
conn.Execute(commandText, paras, commandType: CommandType.Text);
}
}
public async Task<int> ExecuteAsync(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return await conn.ExecuteAsync(commandText, paras, commandType: CommandType.Text);
}
}
public async Task ExecuteAsyncByProc(string procName, object paras = null)
{
using (var conn = NewConn())
{
await conn.ExecuteAsync(procName, paras, commandType: CommandType.StoredProcedure);
}
}
public async Task<IEnumerable<T>> QueryAsync<T>(string commandText, object paras = null, CommandType commandType = CommandType.Text)
{
using (var conn = NewConn())
{
return await conn.QueryAsync<T>(commandText, paras, commandType: commandType);
}
}
public IEnumerable<T> Query<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return conn.Query<T>(commandText, paras, commandType: CommandType.Text);
}
}
public T ExecuteScalarByProc<T>(string procName, object paras = null)
{
using (var conn = NewConn())
{
return conn.ExecuteScalar<T>(procName, paras, commandType: CommandType.StoredProcedure);
}
}
public Task<T> QueryFirstAsyncByProc<T>(string procName, object paras = null)
{
using (var conn = NewConn())
{
return conn.QueryFirstAsync<T>(procName, paras, commandType: CommandType.StoredProcedure);
}
}
public Task ExecuteAsync<T>(string sql, object p)
{
throw new NotImplementedException();
}
public Task<IEnumerable<T>> QueryAsyncByProc<T>(string commandText, object paras = null)
{
using (var conn = NewConn())
{
return conn.QueryAsync<T>(commandText, paras, commandType: CommandType.StoredProcedure);
}
}
#region DataTable、DataSet
public DataTable GetTable(string commandText, object paras = null)
{
using (var conn = NewConn())
{
conn.Open();
using (var reader = conn.ExecuteReader(commandText, paras))
{
var dt = new DataTable();
while (reader.Read())
{
if (dt.Columns.Count == 0)
{
for (var i = 0; i < reader.FieldCount; i++)
{
dt.Columns.Add(reader.GetName(i), reader.GetFieldType(i));
}
}
var row = dt.Rows.Add();
for (var i = 0; i < reader.FieldCount; i++)
{
row[i] = reader.GetValue(i);
}
}
return dt;
}
}
}
public DataSet GetDataSet(string sql, object paras = null, bool isSp = false)
{
using (var conn = NewConn())
{
var ds = new DataSet();
using (var cmd = new SqlCommand(sql, (SqlConnection)conn))
{
if (isSp)
cmd.CommandType = CommandType.StoredProcedure;
if (paras != null)
{
var properties = paras.GetType().GetProperties();
foreach (var property in properties)
{
cmd.Parameters.AddWithValue("@" + property.Name, property.GetValue(paras, null));
}
}
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
return ds;
}
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <param name="isSp"></param>
/// <returns></returns>
public DataTable GetDataTable(string sql, object paras = null, bool isSp = false)
{
using (var conn = NewConn())
{
var dt = new DataTable();
using (var cmd = new SqlCommand(sql, (SqlConnection)conn))
{
if (isSp)
cmd.CommandType = CommandType.StoredProcedure;
if (paras != null)
{
var properties = paras.GetType().GetProperties();
foreach (var property in properties)
{
cmd.Parameters.AddWithValue("@" + property.Name, property.GetValue(paras, null));
}
}
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
return dt;
}
}
#endregion
public void Dispose()
{
if (conn != null)
{
try
{
conn.Dispose();
}
catch
{
}
conn = null;
}
}
}
}

using FluentData;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using test.Extension;
namespace test.DBO
{
/// <summary>
/// 数据库操作类
/// 更换不同数据库,只需修改 NewConn <see cref="NewConn"/> 以及少量代码 <see cref="GetDataSet"/> <see cref="GetDataTable"/>
/// </summary>
public class DbFluentData
{
private string connectionString;
private readonly SqlServerProvider providerMssql = new SqlServerProvider();
public DbFluentData(string conn)
{
connectionString = conn;
}
public IDbContext NewContext()
{
return new DbContext().ConnectionString(connectionString, new SqlServerProvider(), (string)null);
}
#region Insert
/// <summary>
/// 插入元素
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
public void Insert<T>(T model)
{
using (IDbContext context = this.NewContext())
{
context.Insert<T>(typeof(T).Name, model).AutoMap(new Expression<Func<T, object>>[0]).Execute();
}
}
/// <summary>
/// 插入元素,并返回自增长的值.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="model"></param>
/// <param name="keyExpression"></param>
/// <returns></returns>
public TKey Insert<T, TKey>(T model, Expression<Func<T, object>> keyExpression)
{
TKey result;
using (IDbContext context = this.NewContext())
{
result = context.Insert<T>(typeof(T).Name, model).AutoMap(new Expression<Func<T, object>>[]
{
keyExpression
}).ExecuteReturnLastId<TKey>(null);
}
return result;
}
public void Insert<T>(T model, params Expression<Func<T, object>>[] ignoreProperties)
{
using (IDbContext context = this.NewContext())
{
context.Insert<T>(typeof(T).Name, model).AutoMap(ignoreProperties).Execute();
}
}
/// <summary>
/// 往数据库里插入一个字典
/// </summary>
/// <param name="tableName"></param>
/// <param name="dict"></param>
public void Insert(string tableName, Dictionary<string, object> dict)
{
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO ");
sb.Append(tableName);
sb.Append(" ( ");
int i = 0;
foreach (KeyValuePair<string, object> o in dict)
{
if (i > 0)
{
sb.Append(",");
}
i++;
sb.Append(o.Key);
}
sb.Append(") values (");
i = 0;
foreach (KeyValuePair<string, object> o2 in dict)
{
if (i > 0)
{
sb.Append(",");
}
i++;
sb.Append("@").Append(o2.Key);
}
sb.Append(")");
using (IDbContext context = this.NewContext())
{
IDbCommand query = context.Sql(sb.ToString(), new object[0]);
foreach (KeyValuePair<string, object> o3 in dict)
{
query.Parameter(o3.Key, o3.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
query.Execute();
}
}
/// <summary>
/// 往数据库里插入一下字典,并返回自增长键的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <param name="dict"></param>
/// <returns></returns>
public T InsertAndReturnLastId<T>(string tableName, Dictionary<string, object> dict)
{
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO ");
sb.Append(tableName);
sb.Append(" ( ");
int i = 0;
foreach (KeyValuePair<string, object> o in dict)
{
if (i > 0)
{
sb.Append(",");
}
i++;
sb.Append(o.Key);
}
sb.Append(") values (");
i = 0;
foreach (KeyValuePair<string, object> o2 in dict)
{
if (i > 0)
{
sb.Append(",");
}
i++;
sb.Append("@").Append(o2.Key);
}
sb.Append(")");
T result;
using (IDbContext context = this.NewContext())
{
IDbCommand query = context.Sql(sb.ToString(), new object[0]);
foreach (KeyValuePair<string, object> o3 in dict)
{
query.Parameter(o3.Key, o3.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
result = query.ExecuteReturnLastId<T>(null);
}
return result;
}
#endregion
#region Delete
public void DeleteAll<T>()
{
using (IDbContext ctx = this.NewContext())
{
ctx.Sql("delete from " + typeof(T).Name, new object[0]).Execute();
}
}
public void Delete<T>(string keyField, object value)
{
using (IDbContext ctx = this.NewContext())
{
ctx.Sql(string.Format("delete from {0} where {1}=@id", typeof(T).Name, keyField), new object[0]).Parameter("id", value, DataTypes.Object, ParameterDirection.Input, 0).Execute();
}
}
public void Delete<T>(Expression<Func<T, bool>> where)
{
using (IDbContext ctx = this.NewContext())
{
ExpressionExtension.BinaryExpressionInfo bi = where.GetBinaryExpressionInfo();
string keyField = bi.LeftName;
object value = bi.GetRightValue();
ctx.Sql(string.Format("delete from {0} where {1}=@id", typeof(T).Name, keyField), new object[0]).Parameter("id", value, DataTypes.Object, ParameterDirection.Input, 0).Execute();
}
}
#endregion
#region Update
/// <summary>
/// 数据字典内容,更新数据
/// </summary>
/// <param name="tableName"></param>
/// <param name="where"></param>
/// <param name="dict"></param>
public void Update(string tableName, string where, Dictionary<string, object> dict)
{
StringBuilder sb = new StringBuilder();
sb.Append(" UPDATE ");
sb.Append(tableName);
sb.Append(" SET ");
int i = 0;
foreach (KeyValuePair<string, object> o in dict)
{
if (i > 0)
{
sb.Append(",");
}
i++;
sb.Append(o.Key).Append("=@").Append(o.Key);
}
if (!string.IsNullOrEmpty(where))
{
sb.Append(" WHERE ").Append(where);
}
using (IDbContext context = this.NewContext())
{
IDbCommand query = context.Sql(sb.ToString(), new object[0]);
foreach (KeyValuePair<string, object> o2 in dict)
{
query.Parameter(o2.Key, o2.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
query.Execute();
}
}
public void Update(string sql, Dictionary<string, object> dict)
{
using (IDbContext context = this.NewContext())
{
IDbCommand query = context.Sql(sql, new object[0]);
foreach (KeyValuePair<string, object> o2 in dict)
{
query.Parameter(o2.Key, o2.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
query.Execute();
}
}
public void Update<T>(T model, Expression<Func<T, object>> where, params Expression<Func<T, object>>[] ignoreProperties)
{
using (IDbContext context = this.NewContext())
{
context.Update<T>(typeof(T).Name, model).AutoMap(new Expression<Func<T, object>>[]
{
where
}).Where(where, DataTypes.Object, 0).Execute();
}
}
#endregion
#region Select
public T SelectOne<T>(Expression<Func<T, bool>> where)
{
T result;
using (IDbContext ctx = this.NewContext())
{
ExpressionExtension.BinaryExpressionInfo bi = where.GetBinaryExpressionInfo();
string keyField = bi.LeftName;
object value = bi.GetRightValue();
result = ctx.Sql(string.Format("select * from {0} where {1}=@id", typeof(T).Name, keyField), new object[0]).Parameter("id", value, DataTypes.Object, ParameterDirection.Input, 0).QuerySingle<T>(null);
}
return result;
}
public List<T> SelectAll<T>()
{
List<T> result;
using (IDbContext context = this.NewContext())
{
result = context.SelectAll<T>();
}
return result;
}
public List<T> SelectAll<T>(params string[] fields)
{
if (fields == null || fields.Length == 0)
{
throw new ArgumentNullException("fields");
}
string fieldsString = fields.JoinString(",");
List<T> result;
using (IDbContext ctx = this.NewContext())
{
result = ctx.Sql(string.Format("select {0} from {1}", fieldsString, typeof(T).Name), new object[0]).QueryMany<T>(null);
}
return result;
}
/// <summary>
/// 执行一个SQL,返回多行
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public List<T> SelectMany<T>(string sql, params FluentDbParameter[] paras)
{
List<T> result;
using (IDbContext ctx = this.NewContext())
{
FluentData.IDbCommand query = ctx.Sql(sql, new object[0]);
if (paras != null)
{
for (int i = 0; i < paras.Length; i++)
{
FluentDbParameter para = paras[i];
query.Parameter(para.Key, para.Value, DataTypes.Object, FluentData.ParameterDirection.Input, 0);
}
}
result = query.QueryMany<T>(null);
}
return result;
}
#endregion
#region Exec
/// <summary>
/// 执行一个SQL,没有返回任何数据.
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
public void ExecuteNoQuery(string sql, params object[] parameters)
{
using (IDbContext context = this.NewContext())
{
context.Sql(sql, parameters).Execute();
}
}
public void Execute(string sql, Dictionary<string, object> dict)
{
using (IDbContext context = this.NewContext())
{
IDbCommand query = context.Sql(sql, new object[0]);
foreach (KeyValuePair<string, object> o2 in dict)
{
query.Parameter(o2.Key, o2.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
query.Execute();
}
}
public void Execute(string sql, IEnumerable<Dictionary<string, object>> keyValuePairs)
{
using (IDbContext context = this.NewContext().UseTransaction(true))
{
foreach (var dict in keyValuePairs)
{
IDbCommand query = context.Sql(sql, new object[0]);
foreach (KeyValuePair<string, object> o2 in dict)
{
query.Parameter(o2.Key, o2.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
query.Execute();
}
}
}
#endregion
}
public static class IDbContextExtension
{
/// <summary>
/// 自动编辑 select count 语句,并返回结果
/// </summary>
/// <param name="db"></param>
/// <param name="tableName"></param>
/// <param name="whereCondtion">WHERE后面的语句,各参数以p开头,0开始的命名规则.例 " UserID=@p0 and Password=@p1"</param>
/// <param name="paras"></param>
/// <returns></returns>
public static int Count(this IDbContext db, string tableName, string whereCondtion = null, params object[] paras)
{
StringBuilder sql = new StringBuilder();
sql.Append("select count(*) from ").Append(tableName);
if (whereCondtion != null)
{
sql.Append(" WHERE ").Append(whereCondtion);
}
IDbCommand cmd = db.Sql(sql.ToString(), new object[0]);
if (paras != null)
{
for (int i = 0; i < paras.Length; i++)
{
cmd = cmd.Parameter("p" + i, paras[i], DataTypes.Object, ParameterDirection.Input, 0);
}
}
return cmd.QuerySingle<int>(null);
}
public static SelectOneBuilder<T> SelectOne<T>(this IDbContext context)
{
return new SelectOneBuilder<T>(context);
}
/// <summary>
/// 根据条件,求符合条件的记录是否存在.类似本类中的 Count扩展方法
/// </summary>
/// <param name="db"></param>
/// <param name="tableName"></param>
/// <param name="whereCondtion"></param>
/// <param name="paras"></param>
/// <returns></returns>
public static bool Exists(this IDbContext db, string tableName, string whereCondtion = null, params object[] paras)
{
StringBuilder sql = new StringBuilder();
sql.Append("if exists (select * from ").Append(tableName);
if (whereCondtion != null)
{
sql.Append(" WHERE ").Append(whereCondtion);
}
sql.Append(" ) select 1 else select 0");
IDbCommand cmd = db.Sql(sql.ToString(), new object[0]);
if (paras != null)
{
for (int i = 0; i < paras.Length; i++)
{
cmd = cmd.Parameter("p" + i, paras[i], DataTypes.Object, ParameterDirection.Input, 0);
}
}
return cmd.QuerySingle<int>(null) > 0;
}
public static List<T> SelectAll<T>(this IDbContext db)
{
return db.Sql("select * from " + typeof(T).Name, new object[0]).QueryMany<T>(null);
}
}
public class SelectOneBuilder<T>
{
private readonly IDbContext context;
private readonly StringBuilder sb = new StringBuilder();
private readonly Dictionary<string, object> parameters = new Dictionary<string, object>();
public SelectOneBuilder(IDbContext context)
{
this.context = context;
this.sb.Append("SELECT * FROM ").Append(typeof(T).Name).Append(" WHERE 1=1 ");
}
public SelectOneBuilder<T> Where(string columnName, object value)
{
this.sb.Append(" AND ").Append(columnName).Append(" = @").Append(columnName);
this.parameters[columnName] = value;
return this;
}
public SelectOneBuilder<T> Where(Expression<Func<T, bool>> exp)
{
ExpressionExtension.BinaryExpressionInfo expInfo = exp.GetBinaryExpressionInfo();
string columnName = expInfo.LeftName;
object value = expInfo.GetRightValue();
this.sb.Append(" AND ");
ExpressionType nodeType = expInfo.Body.NodeType;
switch (nodeType)
{
case ExpressionType.Equal:
this.sb.AppendFormat("{0} = @{0}", columnName);
goto IL_E5;
case ExpressionType.ExclusiveOr:
case ExpressionType.Invoke:
case ExpressionType.Lambda:
case ExpressionType.LeftShift:
break;
case ExpressionType.GreaterThan:
this.sb.AppendFormat("{0} > @{0}", columnName);
goto IL_E5;
case ExpressionType.GreaterThanOrEqual:
this.sb.AppendFormat("{0} >= @{0}", columnName);
goto IL_E5;
case ExpressionType.LessThan:
this.sb.AppendFormat("{0} < @{0}", columnName);
goto IL_E5;
case ExpressionType.LessThanOrEqual:
this.sb.AppendFormat("{0} <= @{0}", columnName);
goto IL_E5;
default:
if (nodeType == ExpressionType.NotEqual)
{
this.sb.AppendFormat("{0} != @{0}", columnName);
goto IL_E5;
}
break;
}
throw new NotImplementedException();
IL_E5:
this.parameters[columnName] = value;
return this;
}
public T Execute()
{
string sql = this.sb.ToString();
IDbCommand cmd = this.context.Sql(sql, new object[0]);
foreach (KeyValuePair<string, object> p in this.parameters)
{
cmd.Parameter(p.Key, p.Value, DataTypes.Object, ParameterDirection.Input, 0);
}
return cmd.QuerySingle<T>(null);
}
}
public struct FluentDbParameter
{
public string Key;
public object Value;
public FluentDbParameter(string k, object v)
{
this.Key = k;
this.Value = v;
}
}
}
This diff is collapsed.
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Data.SqlClient;
namespace test.Extension
{
public static partial class DataTableExtension
{
public static List<string> GetFields(this DataTable dataTable)
{
List<string> lstFieldName = new List<string>();
foreach (DataColumn column in dataTable.Columns)
{
lstFieldName.Add(column.ColumnName);
}
return lstFieldName;
}
public static string GetInsertCommand(this DataTable dataTable, string tableName)
{
List<string> lstFieldName = dataTable.GetFields();
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO ");
sb.Append(tableName);
sb.Append(" ( ");
sb.Append(lstFieldName.JoinString(","));
sb.Append(") values (");
sb.Append("@");
sb.Append(lstFieldName.JoinString(",@"));
sb.Append(")");
return sb.ToString();
}
public static string GetUpdateCommand(List<string> tabColumns, string tableName, string primaryKeyName)
{
List<string> lstFieldName = new List<string>();
tabColumns.ForEach(field =>
{
if (field != primaryKeyName) lstFieldName.Add($"{field} = @{field}");
});
StringBuilder sb = new StringBuilder();
sb.Append(" Update ");
sb.Append(tableName);
sb.Append(" Set ");
sb.Append(lstFieldName.JoinString(","));
sb.Append($" Where {primaryKeyName} = @{primaryKeyName};");
return sb.ToString();
}
public static string GetUpdateCommand(this DataTable dataTable, string tableName, string primaryKeyName)
{
List<string> lstFieldName = new List<string>();
foreach (DataColumn column in dataTable.Columns)
{
if (column.ColumnName == primaryKeyName) continue;
lstFieldName.Add($"{column.ColumnName} = @{column.ColumnName}");
}
StringBuilder sb = new StringBuilder();
sb.Append(" Update ");
sb.Append(tableName);
sb.Append(" Set ");
sb.Append(lstFieldName.JoinString(","));
sb.Append($" Where {primaryKeyName} = @{primaryKeyName};");
return sb.ToString();
}
public static KeyValuePair<string, IEnumerable<Dictionary<string, object>>> GetInsertCommandWithParam(this DataTable dataTable, string tableName)
{
return new KeyValuePair<string, IEnumerable<Dictionary<string, object>>>(dataTable.GetInsertCommand(tableName), dataTable.GetFieldValues());
}
public static IEnumerable<Dictionary<string, object>> GetFieldValues(this DataTable dataTable)
{
var lstDic = new List<Dictionary<string, object>>();
for (var i = 0; i < dataTable.Rows.Count; i++)
{
var row = dataTable.Rows[i];
var dic = new Dictionary<string, object>();
for (var j = 0; j < dataTable.Columns.Count; j++)
{
var oValue = row[j];
dic.Add(dataTable.Columns[j].ColumnName, oValue != System.DBNull.Value ? oValue : null);
}
lstDic.Add(dic);
}
return lstDic;
}
public static List<SqlParameter[]> GetSqlParameter(this DataTable dataTable)
{
var lstParam = new List<SqlParameter[]>();
for (var i = 0; i < dataTable.Rows.Count; i++)
{
var parameters = new List<SqlParameter>();
for (var j = 0; j < dataTable.Columns.Count; j++)
{
parameters.Add(new SqlParameter(dataTable.Columns[j].ColumnName, dataTable.Rows[i][j]));
}
lstParam.Add(parameters.ToArray());
}
return lstParam;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace test.Extension
{
public static class ExpressionExtension
{
public struct BinaryExpressionInfo
{
public BinaryExpression Body;
public MemberExpression Left;
public Expression Right;
public string LeftName;
public object GetRightValue()
{
if (this.Right is MemberExpression)
{
return this.getMemberExpressionValue((MemberExpression)this.Right);
}
if (this.Right is ConstantExpression)
{
return this.getConstantExpressionValue((ConstantExpression)this.Right);
}
throw new Exception("未实现的Expression类型:" + this.Right.GetType().FullName);
}
private object getConstantExpressionValue(ConstantExpression r)
{
return r.Value;
}
private object getMemberExpressionValue(MemberExpression r)
{
if (r.Expression is ConstantExpression)
{
object rightValue = ((ConstantExpression)r.Expression).Value;
return ((FieldInfo)r.Member).GetValue(rightValue);
}
if (r.Expression is MemberExpression)
{
return Expression.Lambda(r, new ParameterExpression[0]).Compile().DynamicInvoke(new object[0]);
}
throw new Exception("未能处理表达式的右侧的值");
}
}
public static string GetOneName(this Expression exp)
{
return ((PropertyInfo)((MemberExpression)((LambdaExpression)exp).Body).Member).Name;
}
public static ExpressionExtension.BinaryExpressionInfo GetBinaryExpressionInfo(this Expression exp)
{
ExpressionExtension.BinaryExpressionInfo info = default(ExpressionExtension.BinaryExpressionInfo);
info.Body = (BinaryExpression)((LambdaExpression)exp).Body;
info.Left = (MemberExpression)info.Body.Left;
info.Right = info.Body.Right;
info.LeftName = info.Left.Member.Name;
return info;
}
public static string JoinString<T>(this IEnumerable<T> source, string separator)
{
return string.Join<T>(separator, source);
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test.Extension
{
public static partial class DataTableExtension
{
#region 公共方法(扩展DataTable)
/// <summary>
/// DataTable转换成T
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="table">需转换的数据table</param>
/// <returns></returns>
public static T ToModel<T>(this DataTable table) where T : new()
{
if (table == null || table.Columns.Count == 0 || table.Rows.Count == 0) return default(T);
var propertyInfos = from propertyInfo in typeof(T).GetProperties()
where table.Columns.Contains(propertyInfo.Name)
select propertyInfo;
return DataRowToModel<T>(propertyInfos, table.Rows[0]);
//T entity = new T();
//DataRow dr = table.Rows[0];
//foreach (var pi in propertyInfos)
//{
// if (!pi.CanWrite) continue;
// object value = dr[pi.Name];
// if (value != DBNull.Value)
// pi.SetValue(entity, ChangeType(dr[pi.Name], pi.PropertyType), null);
//}
//return entity;
}
/// <summary>
/// DataTable转换成List<T>
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="table">需转换的数据table</param>
/// <returns></returns>
public static List<T> ToModelList<T>(this DataTable table) where T : new()
{
List<T> entities = new List<T>();
if (table == null || table.Columns.Count == 0 || table.Rows.Count == 0) return entities;
var propertyInfos = from propertyInfo in typeof(T).GetProperties()
where table.Columns.Contains(propertyInfo.Name)
select propertyInfo;
foreach (DataRow dr in table.Rows)
{
entities.Add(DataRowToModel<T>(propertyInfos, dr));
}
return entities;
//foreach (DataRow dr in table.Rows)
//{
// T entity = new T();
// foreach (var pi in propertyInfos)
// {
// if (!pi.CanWrite) continue;
// object value = dr[pi.Name];
// if (value != DBNull.Value)
// pi.SetValue(entity, ChangeType(dr[pi.Name], pi.PropertyType), null);
// }
// entities.Add(entity);
//}
//return entities;
}
#endregion 公共方法(扩展DataTable)
#region 私有方法(Convert.ChangeType处理Nullable<>和非Nullable<>)
private static T DataRowToModel<T>(IEnumerable<System.Reflection.PropertyInfo> propertyInfos, DataRow dataRow) where T : new()
{
T entity = new T();
foreach (var pi in propertyInfos)
{
if (!pi.CanWrite) continue;
object value = dataRow[pi.Name];
if (value != DBNull.Value || pi.PropertyType == typeof(string)) // 为null的字符串需要转化为""
pi.SetValue(entity, ChangeType(dataRow[pi.Name], pi.PropertyType), null);
}
return entity;
}
/// <summary>
/// 类型转换(包含Nullable<>和非Nullable<>转换)
/// </summary>
/// <param name="value"></param>
/// <param name="conversionType"></param>
/// <returns></returns>
private static object ChangeType(object value, Type conversionType)
{
// Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
// checking properties on conversionType below.
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
} // end if
// If it's not a nullable type, just pass through the parameters to Convert.ChangeType
if (conversionType.IsGenericType &&
conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
// It's a nullable type, and not null, so that means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
// Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
// nullable type), pass the call on to Convert.ChangeType
return Convert.ChangeType(value, conversionType);
}
#endregion 私有方法(Convert.ChangeType处理Nullable<>和非Nullable<>)
}
}

namespace test
{
partial class FrmDbo
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnDapper = new System.Windows.Forms.Button();
this.btnFluent = new System.Windows.Forms.Button();
this.btnSqlHelper = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.btnClear = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnDapper
//
this.btnDapper.Location = new System.Drawing.Point(25, 23);
this.btnDapper.Name = "btnDapper";
this.btnDapper.Size = new System.Drawing.Size(75, 23);
this.btnDapper.TabIndex = 1;
this.btnDapper.Text = "RunDraaper";
this.btnDapper.UseVisualStyleBackColor = true;
this.btnDapper.Click += new System.EventHandler(this.btnDapper_Click);
//
// btnFluent
//
this.btnFluent.Location = new System.Drawing.Point(128, 23);
this.btnFluent.Name = "btnFluent";
this.btnFluent.Size = new System.Drawing.Size(75, 23);
this.btnFluent.TabIndex = 2;
this.btnFluent.Text = "RunFluent";
this.btnFluent.UseVisualStyleBackColor = true;
this.btnFluent.Click += new System.EventHandler(this.btnFluent_Click);
//
// btnSqlHelper
//
this.btnSqlHelper.Location = new System.Drawing.Point(231, 23);
this.btnSqlHelper.Name = "btnSqlHelper";
this.btnSqlHelper.Size = new System.Drawing.Size(75, 23);
this.btnSqlHelper.TabIndex = 3;
this.btnSqlHelper.Text = "RunSqlHelper";
this.btnSqlHelper.UseVisualStyleBackColor = true;
this.btnSqlHelper.Click += new System.EventHandler(this.btnSqlHelper_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(12, 55);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(420, 241);
this.textBox1.TabIndex = 4;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(335, 23);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(75, 23);
this.btnClear.TabIndex = 5;
this.btnClear.Text = "清空";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// FrmDbo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(444, 308);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.btnSqlHelper);
this.Controls.Add(this.btnFluent);
this.Controls.Add(this.btnDapper);
this.Name = "FrmDbo";
this.Text = "FrmOrm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnDapper;
private System.Windows.Forms.Button btnFluent;
private System.Windows.Forms.Button btnSqlHelper;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button btnClear;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment