|
@@ -0,0 +1,455 @@
|
|
|
+/*-------------------------------------------------------------------------
|
|
|
+ * 功能描述:AbstracDal
|
|
|
+ * 作者:xulisong
|
|
|
+ * 创建时间: 2019/2/27 9:34:38
|
|
|
+ * 版本号:v1.0
|
|
|
+ * -------------------------------------------------------------------------*/
|
|
|
+
|
|
|
+using System;
|
|
|
+using System.Collections;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.Data;
|
|
|
+using System.Data.Common;
|
|
|
+using System.Data.SQLite;
|
|
|
+using System.Linq;
|
|
|
+using System.Text;
|
|
|
+using System.Threading.Tasks;
|
|
|
+
|
|
|
+namespace Saga.Framework.DB
|
|
|
+{
|
|
|
+ public abstract class AbstractDal<T> where T:new ()
|
|
|
+ {
|
|
|
+ /// <summary>
|
|
|
+ /// 默认构造函数
|
|
|
+ /// </summary>
|
|
|
+ public AbstractDal()
|
|
|
+ {
|
|
|
+ }
|
|
|
+ /// <summary>
|
|
|
+ /// 指定表名以及主键,对基类进构造
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="tableName">表名</param>
|
|
|
+ /// <param name="primaryKey">表主键</param>
|
|
|
+ public AbstractDal(string tableName, string primaryKey)
|
|
|
+ {
|
|
|
+ this.TableName = tableName;
|
|
|
+ this.PrimaryKey = primaryKey;
|
|
|
+ this.DefaultSortField = primaryKey;
|
|
|
+ }
|
|
|
+ /// <summary>
|
|
|
+ /// 连接字符串
|
|
|
+ /// </summary>
|
|
|
+ protected string ConnectionString { get; set; }
|
|
|
+ /// <summary>
|
|
|
+ /// 表名称
|
|
|
+ /// </summary>
|
|
|
+ protected string TableName { get; set; }
|
|
|
+ /// <summary>
|
|
|
+ /// 主件
|
|
|
+ /// </summary>
|
|
|
+ protected string PrimaryKey { get; set; }
|
|
|
+ /// <summary>
|
|
|
+ /// 参数化占位符
|
|
|
+ /// </summary>
|
|
|
+ protected string ParameterPrefix { get; set; } = "@";
|
|
|
+ /// <summary>
|
|
|
+ /// 安全的字段信息
|
|
|
+ /// </summary>
|
|
|
+ protected string SafeFieldFormat { get; set; } = "[{0}]";
|
|
|
+
|
|
|
+ protected string DefaultSortField { get; set; }
|
|
|
+ #region 转化相关类
|
|
|
+
|
|
|
+ public abstract Database CreateDatabase();
|
|
|
+ protected abstract DbParameter CreatePrimaryKeyParameter(object key);
|
|
|
+
|
|
|
+ protected virtual T ReaderToEntity(IDataReader dr)
|
|
|
+ {
|
|
|
+ T t = Activator.CreateInstance<T>();
|
|
|
+ System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties();
|
|
|
+ System.Reflection.PropertyInfo[] array = properties;
|
|
|
+ for (int i = 0; i < array.Length; i++)
|
|
|
+ {
|
|
|
+ System.Reflection.PropertyInfo propertyInfo = array[i];
|
|
|
+ try
|
|
|
+ {
|
|
|
+ if (dr[propertyInfo.Name].ToString() != "")
|
|
|
+ {
|
|
|
+ propertyInfo.SetValue(t, dr[propertyInfo.Name] ?? "", null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ catch
|
|
|
+ {
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return t;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected virtual Hashtable EntityToRecord(T obj)
|
|
|
+ {
|
|
|
+ Hashtable hashtable = new Hashtable();
|
|
|
+ System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties();
|
|
|
+ for (int i = 0; i < properties.Length; i++)
|
|
|
+ {
|
|
|
+ object value = properties[i].GetValue(obj, null);
|
|
|
+ value = ((value == null) ? DBNull.Value : value);
|
|
|
+ if (!hashtable.ContainsKey(properties[i].Name))
|
|
|
+ {
|
|
|
+ hashtable.Add(properties[i].Name, value);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return hashtable;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected virtual string GetSafeFileName(string fieldName)
|
|
|
+ {
|
|
|
+ return string.Format(this.SafeFieldFormat, fieldName);
|
|
|
+ }
|
|
|
+ protected virtual string GetParameterPlaceholder(string fieldName)
|
|
|
+ {
|
|
|
+ return string.Format("{0}{1}", ParameterPrefix, fieldName);
|
|
|
+ }
|
|
|
+ /// <summary>
|
|
|
+ /// 获取参数相关维护
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="db"></param>
|
|
|
+ /// <param name="recordFields"></param>
|
|
|
+ /// <returns></returns>
|
|
|
+ protected virtual List<DbParameter> GetDbParameters(Database db, Hashtable recordFields)
|
|
|
+ {
|
|
|
+ List<DbParameter> parameters = new List<DbParameter>();
|
|
|
+ foreach (string fieldName in recordFields.Keys)
|
|
|
+ {
|
|
|
+ object value = recordFields[fieldName];
|
|
|
+ value = (value ?? DBNull.Value);
|
|
|
+ if (value is DateTime)
|
|
|
+ {
|
|
|
+ if (Convert.ToDateTime(value) <= DateTime.MinValue)
|
|
|
+ {
|
|
|
+ value = DBNull.Value;
|
|
|
+ }
|
|
|
+
|
|
|
+ parameters.Add(db.CreateParameter(fieldName, DbType.DateTime, value));
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ parameters.Add(db.CreateParameter(fieldName, value));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return parameters;
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ #region 验证相关类
|
|
|
+ protected void ValidateInput(string condition)
|
|
|
+ {
|
|
|
+ if (DatabaseUtil.HasInjection(condition))
|
|
|
+ {
|
|
|
+ throw new Exception("检测出SQL注入的恶意数据:" + condition);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+ #region 方法执行
|
|
|
+ #region 查找,查找方式有很多
|
|
|
+ public virtual bool ExistByKey(object key)
|
|
|
+ {
|
|
|
+ string arg = string.Format("{0} = {1}{0}", this.PrimaryKey, this.ParameterPrefix);
|
|
|
+ string commandText = string.Format("Select Count(*) from {0} WHERE {1} ", TableName, arg);
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ return Convert.ToInt32(database.ExecuteScalar(commandText, CreatePrimaryKeyParameter(key))) > 0;
|
|
|
+ }
|
|
|
+ public virtual bool ExistByCondition(string condition)
|
|
|
+ {
|
|
|
+ ValidateInput(condition);
|
|
|
+ string commandText = string.Format("Select Count(*) from {0} WHERE {1} ", TableName, condition);
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ return Convert.ToInt32(database.ExecuteScalar(commandText)) > 0;
|
|
|
+ }
|
|
|
+ public virtual T FindByKey(object key)
|
|
|
+ {
|
|
|
+ string condition = string.Format("{0} = {1}{0}", this.PrimaryKey, this.ParameterPrefix);
|
|
|
+ return FindSingle(condition, null, CreatePrimaryKeyParameter(key));
|
|
|
+ }
|
|
|
+ public virtual T FindSingle(string condition)
|
|
|
+ {
|
|
|
+ return FindSingle(condition, null);
|
|
|
+ }
|
|
|
+ public virtual T FindSingle(string condition, string orderBy)
|
|
|
+ {
|
|
|
+ return FindSingle(condition, orderBy, null);
|
|
|
+ }
|
|
|
+ public virtual T FindSingle(string condition, string orderBy, params DbParameter[] parameters)
|
|
|
+ {
|
|
|
+ ValidateInput(condition);
|
|
|
+ ValidateInput(orderBy);
|
|
|
+ T result = default(T);
|
|
|
+ string commandText = string.Format("Select * From {0} ", TableName);
|
|
|
+ if (!string.IsNullOrWhiteSpace(condition))
|
|
|
+ {
|
|
|
+ commandText += string.Format("Where {0} ", condition);
|
|
|
+ }
|
|
|
+ if (!string.IsNullOrWhiteSpace(orderBy))
|
|
|
+ {
|
|
|
+ commandText = commandText + " " + orderBy;
|
|
|
+ }
|
|
|
+ else if(!string.IsNullOrWhiteSpace(DefaultSortField))
|
|
|
+ {
|
|
|
+ commandText = commandText + "" + "order by " + DefaultSortField + " ASC";
|
|
|
+ }
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ using (IDataReader dataReader = database.ExecuteReader(commandText, parameters))
|
|
|
+ {
|
|
|
+ if (dataReader.Read())
|
|
|
+ {
|
|
|
+ result = this.ReaderToEntity(dataReader);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ public virtual List<T> Find(string condition)
|
|
|
+ {
|
|
|
+ return Find(condition, null);
|
|
|
+ }
|
|
|
+ public virtual List<T> Find(string condition, string orderBy)
|
|
|
+ {
|
|
|
+ return Find(condition, orderBy, null);
|
|
|
+ }
|
|
|
+ public virtual List<T> Find(string condition, string orderBy, params DbParameter[] parameters)
|
|
|
+ {
|
|
|
+ ValidateInput(condition);
|
|
|
+ ValidateInput(orderBy);
|
|
|
+ T result = default(T);
|
|
|
+ string commandText = string.Format("Select * From {0} ", TableName);
|
|
|
+ if (!string.IsNullOrEmpty(condition))
|
|
|
+ {
|
|
|
+ commandText += string.Format("Where {0} ", condition);
|
|
|
+ }
|
|
|
+ if (!string.IsNullOrEmpty(orderBy))
|
|
|
+ {
|
|
|
+ commandText = commandText + " " + orderBy;
|
|
|
+ }
|
|
|
+ else if (!string.IsNullOrWhiteSpace(DefaultSortField))
|
|
|
+ {
|
|
|
+ commandText = commandText + "" + "Order by " + DefaultSortField + " ASC";
|
|
|
+ }
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ List<T> list = new List<T>();
|
|
|
+ using (System.Data.IDataReader dataReader = database.ExecuteReader(commandText, parameters))
|
|
|
+ {
|
|
|
+ while (dataReader.Read())
|
|
|
+ {
|
|
|
+ var item = this.ReaderToEntity(dataReader);
|
|
|
+ list.Add(item);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return list;
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ #region 删除
|
|
|
+ public virtual bool DeleteByKey(object key)
|
|
|
+ {
|
|
|
+ return DeleteByKey(key, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ public virtual bool DeleteByCondition(string condition)
|
|
|
+ {
|
|
|
+ return DeleteByCondition(condition, null);
|
|
|
+ }
|
|
|
+ public virtual bool DeleteByKey(object key, DbTransaction trans)
|
|
|
+ {
|
|
|
+ string arg = string.Format("{0} = {1}{0}", this.PrimaryKey, this.ParameterPrefix);
|
|
|
+ string sqlText = string.Format("DELETE FROM {0} WHERE {1} ", this.TableName, arg);
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ return database.ExecuteNonQuery(sqlText, CreatePrimaryKeyParameter(key)) > 0;
|
|
|
+ }
|
|
|
+ public virtual bool DeleteByCondition(string condition, DbTransaction trans)
|
|
|
+ {
|
|
|
+ bool result = false;
|
|
|
+ ValidateInput(condition);
|
|
|
+ string sqlText = string.Format("DELETE FROM {0} WHERE {1} ", this.TableName, condition);
|
|
|
+ Database database = CreateDatabase();
|
|
|
+ if (trans != null)
|
|
|
+ {
|
|
|
+ result = database.ExecuteNonQuery(sqlText, trans) > 0;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ result = database.ExecuteNonQuery(sqlText) > 0;
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ #region 添加
|
|
|
+ public virtual bool Insert(T t)
|
|
|
+ {
|
|
|
+ return Insert(EntityToRecord(t), null);
|
|
|
+ }
|
|
|
+ public virtual bool Insert(T t, DbTransaction trans)
|
|
|
+ {
|
|
|
+ return Insert(EntityToRecord(t), trans);
|
|
|
+ }
|
|
|
+ public virtual bool Insert(Hashtable recordFields, DbTransaction trans)
|
|
|
+ {
|
|
|
+ bool flag = false;
|
|
|
+ bool result;
|
|
|
+ if (recordFields == null || recordFields.Count < 1)
|
|
|
+ {
|
|
|
+ result = flag;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ string intoText = "";
|
|
|
+ string valueText = "";
|
|
|
+ foreach (string fieldName in recordFields.Keys)
|
|
|
+ {
|
|
|
+ intoText += string.Format("{0},", this.GetSafeFileName(fieldName));
|
|
|
+ valueText += string.Format("{0},", this.GetParameterPlaceholder(fieldName));
|
|
|
+ }
|
|
|
+ intoText = intoText.Trim(',');
|
|
|
+ valueText = valueText.Trim(',');
|
|
|
+ string commandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", TableName, intoText, valueText);
|
|
|
+ Database database = this.CreateDatabase();
|
|
|
+ List<DbParameter> parameters = GetDbParameters(database,recordFields);
|
|
|
+ if (trans != null)
|
|
|
+ {
|
|
|
+ flag = (database.ExecuteNonQuery(commandText, trans, parameters.ToArray()) > 0);
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ flag = (database.ExecuteNonQuery(commandText, parameters.ToArray()) > 0);
|
|
|
+ }
|
|
|
+ result = flag;
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ public virtual object InsertAddGetKey(T t)
|
|
|
+ {
|
|
|
+ return InsertAddGetKey(EntityToRecord(t), null);
|
|
|
+ }
|
|
|
+ public virtual object InsertAddGetKey(T t, DbTransaction trans)
|
|
|
+ {
|
|
|
+ return InsertAddGetKey(EntityToRecord(t), trans);
|
|
|
+ }
|
|
|
+ public virtual object InsertAddGetKey(Hashtable recordFields, DbTransaction trans)
|
|
|
+ {
|
|
|
+ object result = null;
|
|
|
+ if (recordFields == null || recordFields.Count < 1)
|
|
|
+ {
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ string intoText = "";
|
|
|
+ string valueText = "";
|
|
|
+ foreach (string fieldName in recordFields.Keys)
|
|
|
+ {
|
|
|
+ intoText += string.Format("{0},", this.GetSafeFileName(fieldName));
|
|
|
+ valueText += string.Format("{0},", this.GetParameterPlaceholder(fieldName));
|
|
|
+ }
|
|
|
+ intoText = intoText.Trim(',');
|
|
|
+ valueText = valueText.Trim(',');
|
|
|
+ string commandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2});Select LAST_INSERT_ROWID()", TableName, intoText, valueText);
|
|
|
+ Database database = this.CreateDatabase();
|
|
|
+ List<DbParameter> parameters = new List<DbParameter>();
|
|
|
+ foreach (string fieldName in recordFields.Keys)
|
|
|
+ {
|
|
|
+ object value = recordFields[fieldName];
|
|
|
+ value = (value ?? DBNull.Value);
|
|
|
+ if (value is DateTime)
|
|
|
+ {
|
|
|
+ if (Convert.ToDateTime(value) <= DateTime.MinValue)
|
|
|
+ {
|
|
|
+ value = DBNull.Value;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ parameters.Add(database.CreateParameter(fieldName, value));
|
|
|
+ }
|
|
|
+ if (trans != null)
|
|
|
+ {
|
|
|
+ result = database.ExecuteScalar(commandText, trans, parameters.ToArray());
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ result = database.ExecuteScalar(commandText, parameters.ToArray());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ #region 修改
|
|
|
+ public virtual bool Update(T obj, object primaryKeyValue)
|
|
|
+ {
|
|
|
+ string condition = string.Format("{0} = {1}{0}", this.PrimaryKey, this.ParameterPrefix);
|
|
|
+ return UpdateByCondition(EntityToRecord(obj), condition, null, CreatePrimaryKeyParameter(primaryKeyValue));
|
|
|
+ }
|
|
|
+
|
|
|
+ public virtual bool Update(T obj, object primaryKeyValue, DbTransaction trans)
|
|
|
+ {
|
|
|
+ string condition = string.Format("{0} = {1}{0}", this.PrimaryKey, this.ParameterPrefix);
|
|
|
+ return UpdateByCondition(EntityToRecord(obj), condition, trans, CreatePrimaryKeyParameter(primaryKeyValue));
|
|
|
+ }
|
|
|
+ public virtual bool UpdateByCondition(T obj, string condition)
|
|
|
+ {
|
|
|
+ return UpdateByCondition(obj, condition, null);
|
|
|
+ }
|
|
|
+ public virtual bool UpdateByCondition(T obj, string condition, DbTransaction trans)
|
|
|
+ {
|
|
|
+ return UpdateByCondition(EntityToRecord(obj), condition, trans);
|
|
|
+ }
|
|
|
+
|
|
|
+ public virtual bool UpdateByCondition(Hashtable recordFields, string condition, DbTransaction trans, params DbParameter[] conditionParameters)
|
|
|
+ {
|
|
|
+ bool result;
|
|
|
+ try
|
|
|
+ {
|
|
|
+ if (recordFields == null || recordFields.Count < 1)
|
|
|
+ {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ recordFields.Remove(this.PrimaryKey);
|
|
|
+ if (recordFields.Count < 1)
|
|
|
+ {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ string setText = "";
|
|
|
+ foreach (string fieldName in recordFields.Keys)
|
|
|
+ {
|
|
|
+ setText += string.Format("{0} = {1},", this.GetSafeFileName(fieldName), this.GetParameterPlaceholder(fieldName));
|
|
|
+ }
|
|
|
+ string query = string.Format("UPDATE {0} SET {1} WHERE {2} ", new object[]
|
|
|
+ {
|
|
|
+ TableName,
|
|
|
+ setText.Substring(0, setText.Length - 1),
|
|
|
+ condition
|
|
|
+ });
|
|
|
+ Database database = this.CreateDatabase();
|
|
|
+ bool flag = false;
|
|
|
+ List<DbParameter> parameters = GetDbParameters(database, recordFields);
|
|
|
+ parameters.AddRange(conditionParameters.ToArray());
|
|
|
+ if (trans != null)
|
|
|
+ {
|
|
|
+ flag = (database.ExecuteNonQuery(query, trans, parameters.ToArray()) > 0);
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ flag = (database.ExecuteNonQuery(query, parameters.ToArray()) > 0);
|
|
|
+ }
|
|
|
+ result = flag;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ catch (System.Exception ex)
|
|
|
+ {
|
|
|
+ throw;
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ #endregion
|
|
|
+ #endregion
|
|
|
+ }
|
|
|
+}
|