BaseDataOperate.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. using System;
  2. using System.Data;
  3. using System.Text;
  4. using System.Data.SqlClient;
  5. using System.Collections.Generic;
  6. using LYFZ.Helper;
  7. using System.Reflection;
  8. using System.Collections.Concurrent;
  9. using System.Linq.Expressions;
  10. using System.Collections;
  11. using System.Linq;
  12. using LYFZ.WinAPI;
  13. using System.Dynamic;
  14. using Newtonsoft.Json;
  15. namespace LYFZ.CloudServerData.DAL
  16. {
  17. /// <summary>
  18. /// 数据操作抽象基类
  19. /// </summary>
  20. public abstract class BaseDataOperate<T>
  21. {
  22. #region 属性
  23. LYFZ.CloudServerData.Model.DBConnection _DBConn;
  24. /// <summary>
  25. /// 当前数据库连接对象
  26. /// </summary>
  27. protected LYFZ.CloudServerData.Model.DBConnection DBConn
  28. {
  29. get
  30. {
  31. return this._DBConn;
  32. }
  33. set
  34. {
  35. this._DBConn = value;
  36. }
  37. }
  38. /// <summary>
  39. /// 获取当前新的数据表模型对象
  40. /// </summary>
  41. public T ObjModel
  42. {
  43. get
  44. {
  45. return Activator.CreateInstance<T>();
  46. }
  47. }
  48. /// <summary>
  49. /// 数据表名
  50. /// </summary>
  51. public string TableName
  52. {
  53. get{
  54. return "tb_"+typeof(T).Name;
  55. }
  56. // set;
  57. }
  58. string _TableFieldNameStr = "";
  59. /// <summary>
  60. /// 数据表字段名字符串,字段名以“,”号分隔
  61. /// </summary>
  62. public string TableFieldNameStr
  63. {
  64. get
  65. {
  66. if (this._TableFieldNameStr.Trim() == "")
  67. {
  68. foreach (string fieldName in this.TableFieldNames)
  69. {
  70. if (this._TableFieldNameStr.Trim() == "")
  71. {
  72. this._TableFieldNameStr += "[" + fieldName + "]";
  73. }
  74. else
  75. {
  76. this._TableFieldNameStr += ",[" + fieldName + "]";
  77. }
  78. }
  79. }
  80. if (this._TableFieldNameStr.Trim() == "")
  81. {
  82. this._TableFieldNameStr = "*";
  83. }
  84. return this._TableFieldNameStr;
  85. }
  86. set { this._TableFieldNameStr = value; }
  87. }
  88. /// <summary>
  89. /// 事物处理
  90. /// </summary>
  91. /// <param name="cmdList"></param>
  92. /// <param name="dbConnection"></param>
  93. /// <returns></returns>
  94. public int ExecuteSqlTran(System.Collections.Generic.List<Helper.CommandInfo> cmdList, Model.DBConnection dbConnection)
  95. {
  96. return Helper.SQLHelper.ExecuteSqlTran(cmdList, dbConnection.GetDBConnectionString());
  97. }
  98. /// <summary>
  99. /// 数据表字段名数组
  100. /// </summary>
  101. public string[] TableFieldNames
  102. {
  103. get
  104. {
  105. System.Reflection.PropertyInfo[] propertyInfos = this.PropertyInfos;
  106. List<string> fieldNameList = new List<string>();
  107. foreach (System.Reflection.PropertyInfo propertyInfo in propertyInfos)
  108. {
  109. if (!propertyInfo.IsSpecialName)
  110. {
  111. fieldNameList.Add(propertyInfo.Name);
  112. }
  113. }
  114. return fieldNameList.ToArray();
  115. }
  116. }
  117. /// <summary>
  118. /// 获取要查询的当前表的字段集合字符串 用","号分隔
  119. /// </summary>
  120. /// <param name="filters"></param>
  121. /// <param name="isContain">如果为true 表示只返回 filters 集合中的字段 如果为false 表示返回排除 filters 集合中的字段以外的所有字段</param>
  122. /// <returns></returns>
  123. public string GetQueryTableFieldNames(string[] filters = null, bool isContain = false)
  124. {
  125. List<string> tempFilters = new List<string>();
  126. if (filters != null)
  127. {
  128. tempFilters.AddRange(filters);
  129. }
  130. System.Reflection.PropertyInfo[] propertyInfos = this.PropertyInfos;
  131. string fieldNames = "";
  132. for (int i = 0; i < propertyInfos.Length; i++)
  133. {
  134. if (!propertyInfos[i].IsSpecialName)
  135. {
  136. System.Reflection.PropertyInfo propertyInfo = propertyInfos[i];
  137. if ((!tempFilters.Contains(propertyInfo.Name) && !isContain) || (tempFilters.Contains(propertyInfo.Name) && isContain))
  138. {
  139. if (fieldNames.Trim().Length <= 0)
  140. {
  141. fieldNames = "[" + propertyInfo.Name + "]";
  142. }
  143. else
  144. {
  145. fieldNames += ",[" + propertyInfo.Name + "]";
  146. }
  147. }
  148. }
  149. }
  150. return fieldNames;
  151. }
  152. /// <summary>
  153. /// 获取属性集合
  154. /// </summary>
  155. public System.Reflection.PropertyInfo[] PropertyInfos
  156. {
  157. get
  158. {
  159. List<System.Reflection.PropertyInfo> list = new List<System.Reflection.PropertyInfo>();
  160. System.Reflection.PropertyInfo[] infos = ObjModel.GetType().GetProperties();
  161. foreach (System.Reflection.PropertyInfo info in infos)
  162. {
  163. if (info.CanWrite)
  164. {
  165. list.Add(info);
  166. }
  167. }
  168. return list.ToArray();
  169. }
  170. }
  171. #endregion
  172. #region 检查记录
  173. /// <summary>
  174. /// 是否存在该记录
  175. /// </summary>
  176. public bool Exists(int id)
  177. {
  178. return this.Exists("ID", id);
  179. }
  180. /// <summary>
  181. /// 根据筛选条件判断是否存在该记录
  182. /// </summary>
  183. /// <param name="filterFieldName">筛选字段名</param>
  184. /// <param name="filterValue">筛选值</param>
  185. /// <returns></returns>
  186. public bool Exists(string filterFieldName, object filterValue)
  187. {
  188. if (filterFieldName != "" && filterValue != null)
  189. {
  190. StringBuilder strSql = new StringBuilder();
  191. strSql.Append("select count(1) from " + this.TableName + " ");
  192. strSql.Append(" where 1=1 and " + filterFieldName + "=@" + filterFieldName);
  193. SqlParameter[] parameters = {
  194. new SqlParameter("@"+filterFieldName, filterValue)
  195. };
  196. return SQLHelper.Exists(strSql.ToString(), this.DBConn.DBConnectionString, parameters);
  197. }
  198. else
  199. {
  200. return false;
  201. }
  202. }
  203. /// <summary>
  204. /// 根据筛选条件判断是否存在该记录
  205. /// </summary>
  206. /// <param name="filterFieldName">筛选字段名</param>
  207. /// <param name="filterValue">筛选值</param>
  208. /// <returns></returns>
  209. public bool Exists(string whereString)
  210. {
  211. if (whereString.Trim().Length > 0)
  212. {
  213. StringBuilder strSql = new StringBuilder();
  214. strSql.Append("select count(1) from " + this.TableName + " ");
  215. strSql.Append(" where " + whereString);
  216. return SQLHelper.Exists(strSql.ToString(), this.DBConn.DBConnectionString);
  217. }
  218. else
  219. {
  220. return false;
  221. }
  222. }
  223. /// <summary>
  224. /// 判断是否存某个字段
  225. /// </summary>
  226. /// <param name="columnName">列名称</param>
  227. /// <returns>是否存在</returns>
  228. public bool ColumnExists(string columnName)
  229. {
  230. return SQLHelper.ColumnExists(this.TableName, columnName, this.DBConn.DBConnectionString);
  231. }
  232. #endregion
  233. #region 公共方法
  234. /// <summary>
  235. /// 获取最大ID()
  236. /// </summary>
  237. /// <returns></returns>
  238. public int GetMaxID()
  239. {
  240. return this.GetMaxID("ID");
  241. }
  242. /// <summary>
  243. /// 获取某字段最大值(获取字段必须为数字类型)
  244. /// </summary>
  245. /// <param name="FieldName">字段名</param>
  246. /// <returns></returns>
  247. public int GetMaxID(string FieldName)
  248. {
  249. return SQLHelper.GetMaxID(FieldName, this.TableName, this.DBConn.DBConnectionString);
  250. }
  251. #endregion
  252. #region 判断方法
  253. /// <summary>
  254. /// 获取是否为忽略字段 返回 true 表示忽略 false 不忽略
  255. /// </summary>
  256. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  257. /// <param name="fieldName">要判断的字段名</param>
  258. /// <returns></returns>
  259. public bool IsOverlookFiel(string overlookFieldList, string fieldName)
  260. {
  261. bool bl = false;
  262. string[] tempOverlookFieldList = overlookFieldList.Split(',');
  263. for (int i = 0; i < tempOverlookFieldList.Length; i++)
  264. {
  265. if (tempOverlookFieldList[i].Trim().ToLower() == fieldName.Trim().ToLower())
  266. {
  267. bl = true;
  268. break;
  269. }
  270. }
  271. return bl;
  272. }
  273. #endregion
  274. #region 增加数据
  275. /// <summary>
  276. /// 增加一条数据
  277. /// </summary>
  278. /// <param name="model">Model对象</param>
  279. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  280. /// <returns></returns>
  281. public bool Add(T model, string overlookFieldList = "ID")
  282. {
  283. LYFZ.Helper.CommandInfo comdInfo = this.GetAddCommandInfo(model, overlookFieldList);
  284. int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
  285. if (rows > 0)
  286. {
  287. return true;
  288. }
  289. else
  290. {
  291. return false;
  292. }
  293. }
  294. /// <summary>
  295. /// 获取插入数CommandInfo对象
  296. /// </summary>
  297. /// <param name="model"></param>
  298. /// <param name="overlookFieldList">要忽略的字段集合 多个字段名有“,”号分隔</param>
  299. /// <returns></returns>
  300. public object GetAddCommandInfoObject(T model, string overlookFieldList = "ID")
  301. {
  302. return this.GetAddCommandInfo(model, overlookFieldList);
  303. }
  304. /// <summary>
  305. /// 获取插入数CommandInfo对象
  306. /// </summary>
  307. /// <param name="model"></param>
  308. /// <param name="overlookFieldList">要忽略的字段集合 多个字段名有“,”号分隔</param>
  309. /// <param name="type"></param>
  310. /// <returns></returns>
  311. public LYFZ.Helper.CommandInfo GetAddCommandInfo(T model, string overlookFieldList = "ID", EffentNextType type = EffentNextType.None)
  312. {
  313. StringBuilder strSql = new StringBuilder();
  314. StringBuilder tempFieldNameString = new StringBuilder();
  315. StringBuilder tempValueVariable = new StringBuilder();
  316. List<SqlParameter> parameterlist = new List<SqlParameter>();
  317. for (int i = 0; i < PropertyInfos.Length; i++)
  318. {
  319. try
  320. {
  321. System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
  322. string tempFieldName = propertyInfo.Name;
  323. object tempValue = propertyInfo.GetValue(model, null);
  324. Type tempType = propertyInfo.PropertyType;
  325. if (!IsOverlookFiel(overlookFieldList, tempFieldName) || (tempFieldName.ToLower() == "id" && tempType == typeof(long)))
  326. {
  327. try
  328. {
  329. if (tempType.Name == "DateTime")
  330. {
  331. if (tempValue.ToString().Contains("0001"))
  332. {
  333. tempValue = null;
  334. }
  335. try
  336. {
  337. DateTime tempTime;
  338. if (!DateTime.TryParse(tempValue.ToString(), out tempTime))
  339. {
  340. tempValue = null;
  341. }
  342. else if (tempTime <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
  343. {
  344. tempValue = null;
  345. }
  346. }
  347. catch
  348. {
  349. tempValue = null;
  350. }
  351. }
  352. else if (tempFieldName.ToLower() == "id" && tempType == typeof(long) && (tempValue == null || Convert.ToInt64(tempValue) == 0))
  353. {
  354. tempValue = LYFZ.WinAPI.CustomPublicMethod.GenerateId();
  355. }
  356. if (tempValue != null)
  357. {
  358. tempFieldNameString.Append("" + tempFieldName + ",");
  359. tempValueVariable.Append("@" + tempFieldName + ",");
  360. SqlParameter parameter = new SqlParameter("@" + tempFieldName, tempValue);
  361. parameterlist.Add(parameter);
  362. }
  363. }
  364. catch { }
  365. }
  366. }
  367. catch { }
  368. }
  369. //去除结尾多余的“,”
  370. if (tempFieldNameString.ToString().LastIndexOf(',') == tempFieldNameString.Length - 1)
  371. {
  372. tempFieldNameString.Remove(tempFieldNameString.Length - 1, 1);
  373. }
  374. //去除结尾多余的“,”
  375. if (tempValueVariable.ToString().LastIndexOf(',') == tempValueVariable.Length - 1)
  376. {
  377. tempValueVariable.Remove(tempValueVariable.Length - 1, 1);
  378. }
  379. strSql.Append("insert into " + this.TableName + "(");
  380. strSql.Append("" + tempFieldNameString.ToString() + ")");
  381. strSql.Append(" values (");
  382. strSql.Append("" + tempValueVariable.ToString() + ")");
  383. strSql.Append(";select @@IDENTITY");
  384. SqlParameter[] parameters = parameterlist.ToArray();
  385. return new CommandInfo(strSql.ToString(), parameters, type);
  386. }
  387. #endregion
  388. #region 更新数据
  389. /// <summary>
  390. /// 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
  391. /// </summary>
  392. /// <param name="model">Model对象</param>
  393. /// <param name="filterFieldName">筛选字段名称</param>
  394. /// <param name="operators">SQL筛选运算符号</param>
  395. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  396. /// <param name="whereStr">Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数</param>
  397. /// <returns></returns>
  398. protected bool InsideUpdate(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
  399. {
  400. LYFZ.Helper.CommandInfo comdInfo = GetUpdateCommandInfo(model, filterFieldName, operators, overlookFieldList, whereStr);
  401. int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
  402. if (rows > 0)
  403. {
  404. return true;
  405. }
  406. else
  407. {
  408. return false;
  409. }
  410. }
  411. ///// <summary>
  412. ///// 获取更新数据的UpdateCommandInfo对象 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
  413. ///// </summary>
  414. ///// <param name="model">Model对象</param>
  415. ///// <param name="filterFieldName">筛选字段名称</param>
  416. ///// <param name="operators">SQL筛选运算符号</param>
  417. ///// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  418. ///// <param name="whereStr">Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数</param>
  419. //public LYFZ.Helper.CommandInfo GetUpdateCommandInfoObject(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
  420. //{
  421. // return this.GetUpdateCommandInfo(model, filterFieldName, operators, overlookFieldList, whereStr);
  422. //}
  423. /// <summary>
  424. /// 获取更新数据的UpdateCommandInfo对象 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
  425. /// </summary>
  426. /// <param name="model">Model对象</param>
  427. /// <param name="filterFieldName">筛选字段名称</param>
  428. /// <param name="operators">SQL筛选运算符号</param>
  429. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  430. /// <param name="whereStr">Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数</param>
  431. /// <param name="type"></param>
  432. public LYFZ.Helper.CommandInfo GetUpdateCommandInfo(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null, EffentNextType type = EffentNextType.None)
  433. {
  434. StringBuilder strSql = new StringBuilder();
  435. strSql.Append("update " + this.TableName + " set ");
  436. List<SqlParameter> parameterlist = new List<SqlParameter>();
  437. overlookFieldList += "," + filterFieldName;
  438. for (int i = 0; i < PropertyInfos.Length; i++)
  439. {
  440. try
  441. {
  442. System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
  443. string tempFieldName = propertyInfo.Name;//字段名
  444. object tempValue = propertyInfo.GetValue(model, null);//对应字段值
  445. //如果字段名不为忽略字段则进行处理
  446. if (!IsOverlookFiel(overlookFieldList, tempFieldName))
  447. {
  448. try
  449. {
  450. if (tempValue.GetType() == typeof(DateTime))
  451. {
  452. DateTime tempTime;
  453. try
  454. {
  455. if (!DateTime.TryParse(tempValue.ToString(), out tempTime))
  456. {
  457. tempValue = null;
  458. }
  459. else if (tempTime <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
  460. {
  461. tempValue = null;
  462. }
  463. else if (tempTime.Year == Convert.ToDateTime("0001-01-01").Year || tempTime.Year == Convert.ToDateTime("1753-01-01").Year)
  464. {
  465. tempValue = null;
  466. }
  467. }
  468. catch { tempValue = null; }
  469. }
  470. }
  471. catch { }
  472. strSql.Append("" + tempFieldName + "=@" + tempFieldName + ",");
  473. SqlParameter parameter = new SqlParameter("@" + tempFieldName, tempValue);
  474. parameterlist.Add(parameter);
  475. }
  476. }
  477. catch { }
  478. }
  479. //去除结尾多余的“,”
  480. if (strSql.ToString().LastIndexOf(',') == strSql.Length - 1)
  481. {
  482. strSql.Remove(strSql.Length - 1, 1);
  483. }
  484. if (whereStr == null)
  485. {
  486. if (filterFieldName != "" && operators != "")
  487. {
  488. try
  489. {
  490. object FilterFieldValue = LYFZ.WinAPI.CustomPublicMethod.GetPropertyValue(model, filterFieldName);// model.GetType().GetProperty(filterFieldName).GetValue(model, null);
  491. strSql.Append(" where " + filterFieldName + operators + "@" + filterFieldName);
  492. parameterlist.Add(new SqlParameter("@" + filterFieldName, FilterFieldValue));
  493. }
  494. catch
  495. {
  496. }
  497. }
  498. }
  499. else
  500. {
  501. strSql.Append(" where 1=1 and (" + whereStr + ")");
  502. }
  503. SqlParameter[] parameters = parameterlist.ToArray();
  504. return new CommandInfo(strSql.ToString(), parameters, type);
  505. }
  506. /// <summary>
  507. /// 根据筛选字段和SQL筛选运算符号更新数据
  508. /// </summary>
  509. /// <param name="model">Model对象</param>
  510. /// <param name="filterFieldName">筛选字段名称</param>
  511. /// <param name="operators">SQL筛选运算符号</param>
  512. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  513. /// <returns></returns>
  514. public bool Update(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID")
  515. {
  516. return InsideUpdate(model, filterFieldName, operators, overlookFieldList);
  517. }
  518. /// <summary>
  519. /// 根据Wher条件更新数据 不建义使用此方法
  520. /// </summary>
  521. /// <param name="model">Model对象</param>
  522. /// <param name="whereStr">Wher条件,不包含“where”关键字</param>
  523. /// <param name="overlookFieldList">忽略字段名列表 字段名之间用“,”号分隔</param>
  524. /// <returns></returns>
  525. public bool Update(T model, string whereStr, string overlookFieldList = "ID")
  526. {
  527. return InsideUpdate(model, overlookFieldList: overlookFieldList, whereStr: whereStr);
  528. }
  529. #endregion
  530. #region 删除数据
  531. /// <summary>
  532. /// 根据筛选字段或where条件删除数据
  533. /// </summary>
  534. /// <param name="filterFieldName">筛选字段名</param>
  535. /// <param name="operators">筛选SQL运算符</param>
  536. /// <param name="filterValue">筛选值</param>
  537. /// <param name="whereStr">Wher条件,不包含“where”关键字</param>
  538. /// <returns></returns>
  539. protected bool InsideDelete(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null)
  540. {
  541. LYFZ.Helper.CommandInfo comdInfo = GetDeleteCommandInfo(filterFieldName, operators, filterValue, whereStr);
  542. int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
  543. if (rows > 0)
  544. {
  545. return true;
  546. }
  547. else
  548. {
  549. return false;
  550. }
  551. }
  552. ///// <summary>
  553. ///// 根据筛选字段或where条件删除数据
  554. ///// </summary>
  555. ///// <param name="filterFieldName">筛选字段名</param>
  556. ///// <param name="operators">筛选SQL运算符</param>
  557. ///// <param name="filterValue">筛选值</param>
  558. ///// <param name="whereStr">Wher条件,传入条件语句时筛选字段无效不建义使用 不包含“where”关键字</param>
  559. ///// <returns></returns>
  560. //public object GetDeleteCommandInfoObject(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null)
  561. //{
  562. // return this.GetDeleteCommandInfo(filterFieldName, operators, filterValue, whereStr);
  563. //}
  564. /// <summary>
  565. /// 根据筛选字段或where条件删除数据
  566. /// </summary>
  567. /// <param name="filterFieldName">筛选字段名</param>
  568. /// <param name="operators">筛选SQL运算符</param>
  569. /// <param name="filterValue">筛选值</param>
  570. /// <param name="whereStr">Wher条件,传入条件语句时筛选字段无效不建义使用 不包含“where”关键字</param>
  571. /// <param name="type"></param>
  572. /// <returns></returns>
  573. public LYFZ.Helper.CommandInfo GetDeleteCommandInfo(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null, EffentNextType type = EffentNextType.None)
  574. {
  575. if (filterValue == null) { filterValue = ""; }
  576. List<SqlParameter> parameterlist = new List<SqlParameter>();
  577. StringBuilder strSql = new StringBuilder();
  578. strSql.Append("delete from " + this.TableName + " ");
  579. if (whereStr == null)
  580. {
  581. strSql.Append(" where " + filterFieldName + "" + operators + "@" + filterFieldName + "");
  582. parameterlist.Add(new SqlParameter("@" + filterFieldName, filterValue));
  583. }
  584. else
  585. {
  586. strSql.Append(" where ID>@ID and (" + whereStr + ")");
  587. parameterlist.Add(new SqlParameter("@ID", Convert.ToInt32(0)));
  588. }
  589. SqlParameter[] parameters = parameterlist.ToArray();
  590. return new CommandInfo(strSql.ToString(), parameters, type);
  591. }
  592. /// <summary>
  593. /// 删除一条数据
  594. /// </summary>
  595. /// <param name="ID">id</param>
  596. public bool Delete(long ID)
  597. {
  598. return this.InsideDelete(filterValue: ID);
  599. }
  600. /// <summary>
  601. /// 删除一条数据
  602. /// </summary>
  603. /// <param name="ID">id</param>
  604. public bool Delete(int ID)
  605. {
  606. return this.InsideDelete(filterValue: ID);
  607. }
  608. /// <summary>
  609. /// 根据筛选字段删除数据
  610. /// </summary>
  611. /// <param name="filterValue">筛选值</param>
  612. /// <param name="filterFieldName">筛选字段名</param>
  613. /// <param name="operators">筛选SQL运算符</param>
  614. /// <returns></returns>
  615. public bool Delete(object filterValue, string filterFieldName = "ID", string operators = "=")
  616. {
  617. return this.InsideDelete(filterFieldName, operators, filterValue);
  618. }
  619. /// <summary>
  620. /// 根据where条件删除数据 不建义使用此方法
  621. /// </summary>
  622. /// <param name="whereStr">Wher条件,不包含“where”关键字</param>
  623. /// <returns></returns>
  624. public bool Delete(string whereStr)
  625. {
  626. return this.InsideDelete(whereStr: whereStr);
  627. }
  628. /// <summary>
  629. /// 批量删除数据
  630. /// </summary>
  631. /// <param name="filterFieldName">筛选字段名</param>
  632. /// <param name="valueList">值列表,多个值用“,”分隔,字符串值用“'”号包含</param>
  633. public bool DeleteList(string filterFieldName, string valueList)
  634. {
  635. if (filterFieldName != "" && valueList != "")
  636. {
  637. StringBuilder strSql = new StringBuilder();
  638. strSql.Append("delete from " + this.TableName + " ");
  639. strSql.Append(" where " + filterFieldName + " in (" + valueList + ") ");
  640. int rows = SQLHelper.ExecuteSql(strSql.ToString(), this.DBConn.DBConnectionString);
  641. if (rows > 0)
  642. {
  643. return true;
  644. }
  645. else
  646. {
  647. return false;
  648. }
  649. }
  650. else
  651. {
  652. return false;
  653. }
  654. }
  655. /// <summary>
  656. /// 按ID列表批量删除数据
  657. /// </summary>
  658. /// <param name="idList">ID列表,多个用“,”分隔</param>
  659. public bool DeleteList(string idList)
  660. {
  661. return this.DeleteList("ID", idList);
  662. }
  663. #endregion
  664. #region 查询数据
  665. public T DataRowToModel(DataRow dr)
  666. {
  667. if (dr == null)
  668. {
  669. return Activator.CreateInstance<T>();
  670. }
  671. Dictionary<string, string> dataInfo = new Dictionary<string, string>();
  672. dynamic objmatch = new ExpandoObject();
  673. for (int i = 0; i < dr.Table.Columns.Count; i++)
  674. {
  675. string value = dr[dr.Table.Columns[i].ColumnName].ToString();
  676. if (!string.IsNullOrEmpty(value))
  677. {
  678. dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
  679. }
  680. }
  681. objmatch = dataInfo;
  682. string json = JsonConvert.SerializeObject((object)objmatch);
  683. return DataRowToModelByEntity(json);
  684. }
  685. public T GetModelObjectByEntity(string filterFieldName, object filterValue)
  686. {
  687. DataRow dr = GetDataRow(filterFieldName, filterValue);
  688. Dictionary<string, string> dataInfo = new Dictionary<string, string>();
  689. if(dr==null)
  690. {
  691. return Activator.CreateInstance<T>();
  692. }
  693. dynamic objmatch = new ExpandoObject();
  694. for (int i = 0; i < dr.Table.Columns.Count; i++)
  695. {
  696. string value = dr[dr.Table.Columns[i].ColumnName].ToString();
  697. if (!string.IsNullOrEmpty(value))
  698. {
  699. dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
  700. }
  701. }
  702. objmatch = dataInfo;
  703. string json = JsonConvert.SerializeObject((object)objmatch);
  704. return DataRowToModelByEntity(json);
  705. }
  706. public T DataRowToModelByEntity(int ID)
  707. {
  708. DataRow dr = GetDataRow(ID);
  709. if (dr == null)
  710. {
  711. return Activator.CreateInstance<T>();
  712. }
  713. Dictionary<string, string> dataInfo = new Dictionary<string, string>();
  714. dynamic objmatch = new ExpandoObject();
  715. for (int i = 0; i < dr.Table.Columns.Count; i++)
  716. {
  717. string value = dr[dr.Table.Columns[i].ColumnName].ToString();
  718. if (!string.IsNullOrEmpty(value))
  719. {
  720. dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
  721. }
  722. }
  723. objmatch = dataInfo;
  724. string json = JsonConvert.SerializeObject((object)objmatch);
  725. return DataRowToModelByEntity(json);
  726. }
  727. T DataRowToModelByEntity(string json)
  728. {
  729. T obj = (T)JsonConvert.DeserializeObject(json, this.ObjModel.GetType());
  730. return obj;
  731. }
  732. /// <summary>
  733. /// 得到一个Object对象实体
  734. /// </summary>
  735. /// <param name="ID"></param>
  736. /// <returns></returns>
  737. public T GetModel(long ID)
  738. {
  739. return DataRowToModel(GetDataRow(ID));
  740. }
  741. /// <summary>
  742. /// 得到一个Object对象实体
  743. /// </summary>
  744. /// <param name="ID"></param>
  745. /// <returns></returns>
  746. public T GetModel(int ID)
  747. {
  748. return DataRowToModel(GetDataRow(ID));
  749. }
  750. /// <summary>
  751. /// 根据筛选条件获取一条数据Model对象
  752. /// </summary>
  753. /// <param name="filterFieldName">筛选条件字段名</param>
  754. /// <param name="filterValue">值</param>
  755. /// <returns></returns>
  756. public T GetModel(string filterFieldName, object filterValue)
  757. {
  758. return DataRowToModel(GetDataRow(filterFieldName, filterValue));
  759. }
  760. /// <summary>
  761. /// 根据筛选条件获取一条数据Model对象
  762. /// </summary>
  763. /// <param name="filterFieldName">筛选条件字段名</param>
  764. /// <param name="filterValue">值</param>
  765. /// <param name="operators">SQL筛选运算符号</param>
  766. /// <returns></returns>
  767. public T GetModel(string filterFieldName, object filterValue, string operators)
  768. {
  769. return DataRowToModel(GetDataRow(filterFieldName, filterValue, operators));
  770. }
  771. /// <summary>
  772. /// 根据筛选条件获取一条数据Model对象
  773. /// </summary>
  774. /// <param name="whereString">筛选条件</param>
  775. /// <returns></returns>
  776. public T GetModel(string whereString)
  777. {
  778. return DataRowToModel(GetDataRow(whereString));
  779. }
  780. /// <summary>
  781. /// 获取一条数据DataRow对象
  782. /// </summary>
  783. /// <param name="ID">id</param>
  784. /// <returns></returns>
  785. public DataRow GetDataRow(long id)
  786. {
  787. return GetDataRow("ID", id);
  788. }
  789. /// <summary>
  790. /// 获取一条数据DataRow对象
  791. /// </summary>
  792. /// <param name="ID">id</param>
  793. /// <returns></returns>
  794. public DataRow GetDataRow(int id)
  795. {
  796. return GetDataRow("ID", id);
  797. }
  798. /// <summary>
  799. /// 根据筛选条件获取一条数据DataRow对象
  800. /// </summary>
  801. /// <param name="whereString">筛选条件</param>
  802. /// <returns></returns>
  803. public DataRow GetDataRow(string whereString)
  804. {
  805. if (whereString.Trim().Length > 0)
  806. {
  807. StringBuilder strSql = new StringBuilder();
  808. strSql.Append("select top 1 " + this.TableFieldNameStr + " from " + this.TableName + " ");
  809. strSql.Append(" where " + whereString);
  810. DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
  811. if (ds.Tables[0].Rows.Count > 0)
  812. {
  813. return ds.Tables[0].Rows[0];
  814. }
  815. else
  816. {
  817. return null;
  818. }
  819. }
  820. else
  821. {
  822. return null;
  823. }
  824. }
  825. /// <summary>
  826. /// 根据筛选条件获取一条数据DataRow对象
  827. /// </summary>
  828. /// <param name="filterFieldName">筛选条件字段名</param>
  829. /// <param name="filterValue">值</param>
  830. /// <param name="operators">SQL筛选运算符号</param>
  831. /// <returns></returns>
  832. public DataRow GetDataRow(string filterFieldName, object filterValue, string operators = "=")
  833. {
  834. if (filterFieldName != "" && filterValue != null)
  835. {
  836. StringBuilder strSql = new StringBuilder();
  837. strSql.Append("select top 1 " + this.TableFieldNameStr + " from " + this.TableName + " ");
  838. strSql.Append(" where 1=1 and " + filterFieldName + "" + operators + "@" + filterFieldName + " ");
  839. SqlParameter[] parameters = {
  840. new SqlParameter("@"+filterFieldName, filterValue)
  841. };
  842. DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString, parameters);
  843. if (ds.Tables[0].Rows.Count > 0)
  844. {
  845. return ds.Tables[0].Rows[0];
  846. }
  847. else
  848. {
  849. return null;
  850. }
  851. }
  852. else
  853. {
  854. return null;
  855. }
  856. }
  857. /// <summary>
  858. /// 根据筛选条件获取一条数据DataRow对象(运算符是“=”)
  859. /// </summary>
  860. /// <param name="filterFieldName">筛选条件字段名</param>
  861. /// <param name="filterValue">值</param>
  862. /// <returns></returns>
  863. public DataRow GetDataRow(string filterFieldName, object filterValue)
  864. {
  865. return GetDataRow(filterFieldName, filterValue, "=");
  866. }
  867. /// <summary>
  868. /// 得到一个对象实体
  869. /// </summary>
  870. public T DataRowToModel(DataRow row, T model)
  871. {
  872. if (row != null)
  873. {
  874. for (int i = 0; i < PropertyInfos.Length; i++)
  875. {
  876. try
  877. {
  878. System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
  879. string tempFieldName = propertyInfo.Name;//字段名
  880. if (row[tempFieldName] != null)
  881. {
  882. object tempValue = row[tempFieldName];//对应字段值
  883. LYFZ.WinAPI.CustomPublicMethod.SetPropertyValue(model, propertyInfo, tempValue);
  884. }
  885. }
  886. catch
  887. {
  888. }
  889. }
  890. }
  891. return model;
  892. }
  893. /// <summary>
  894. /// 获得数据列表
  895. /// </summary>
  896. /// <param name="strWhere">条件语句 不包含 where 关键字</param>
  897. /// <param name="filedOrder">SQL排序 如:id desc</param>
  898. public DataSet GetList(string strWhere, string filedOrder = "ID asc")
  899. {
  900. return this.GetList(0, strWhere, filedOrder);
  901. }
  902. /// <summary>
  903. /// 获得全部数据列表
  904. /// </summary>
  905. /// <param name="filedOrder">SQL排序 如:id desc</param>
  906. public DataSet GetAllList(string filedOrder = "ID asc")
  907. {
  908. return this.GetList("", filedOrder);
  909. }
  910. /// <summary>
  911. /// 获得全部数据列表
  912. /// </summary>
  913. /// <param name="filedOrder">SQL排序 如:id desc</param>
  914. public List<T> GetAllModelList(string filedOrder = "ID asc")
  915. {
  916. DataTable tb = this.GetAllList(filedOrder).Tables[0];
  917. List<T> modelList = new List<T>();
  918. foreach (DataRow row in tb.Rows)
  919. {
  920. modelList.Add(this.DataRowToModel(row));
  921. }
  922. return modelList;
  923. }
  924. /// <summary>
  925. /// 获得前几行数据
  926. /// </summary>
  927. /// <param name="Top">行数</param>
  928. /// <param name="strWhere">条件 不包含 where 关键字</param>
  929. /// <param name="filedOrder">SQL排序 如:id asc</param>
  930. /// <returns></returns>
  931. public DataSet GetList(int Top, string strWhere, string filedOrder = "ID asc")
  932. {
  933. StringBuilder strSql = new StringBuilder();
  934. strSql.Append("select ");
  935. if (Top > 0)
  936. {
  937. strSql.Append(" top " + Top.ToString());
  938. }
  939. strSql.Append(" " + this.TableFieldNameStr + " from " + this.TableName + " ");
  940. if (strWhere.Trim() != "")
  941. {
  942. strSql.Append(" where 1=1 and (" + strWhere + ")");
  943. }
  944. strSql.Append(" order by " + filedOrder);
  945. DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
  946. ds.Tables[0].TableName = this.TableName;
  947. return ds;
  948. }
  949. #endregion
  950. #region 数据分页
  951. /// <summary>
  952. /// 获取记录总数
  953. /// </summary>
  954. public int GetRecordCount(string strWhere)
  955. {
  956. StringBuilder strSql = new StringBuilder();
  957. strSql.Append("select count(1) FROM " + this.TableName + " ");
  958. if (strWhere.Trim() != "")
  959. {
  960. strSql.Append(" where 1=1 and (" + strWhere + ")");
  961. }
  962. object obj = SQLHelper.GetSingle(strSql.ToString(), this.DBConn.DBConnectionString);
  963. if (obj == null)
  964. {
  965. return 0;
  966. }
  967. else
  968. {
  969. return Convert.ToInt32(obj);
  970. }
  971. }
  972. /// <summary>
  973. /// 获取分页后总页数
  974. /// </summary>
  975. /// <param name="strWhere">筛选条件</param>
  976. /// <param name="pageSize">页面大小</param>
  977. /// <returns></returns>
  978. public int GetByPageCount(string strWhere, int pageSize)
  979. {
  980. int pageCount = 0;
  981. if (pageSize > 0)
  982. {
  983. int allCount = GetRecordCount(strWhere);
  984. pageCount = allCount / pageSize;
  985. if (pageCount * pageSize < allCount)
  986. {
  987. pageCount++;
  988. }
  989. }
  990. return pageCount;
  991. }
  992. /// <summary>
  993. /// 分页获取数据列表
  994. /// </summary>
  995. /// <param name="strWhere">筛选条件</param>
  996. /// <param name="pageIndex">当前页 不能小于0的整数</param>
  997. /// <param name="pageSize">页面大小,每页显示条数 不能小于0的整数</param>
  998. /// <param name="orderby">排序</param>
  999. /// <returns></returns>
  1000. public DataSet GetListByPage(string strWhere, int pageIndex, int pageSize, string orderby = "id desc")
  1001. {
  1002. return this.GetListByPage(strWhere, orderby, (pageIndex - 1) * pageSize, pageIndex * pageSize);
  1003. }
  1004. /// <summary>
  1005. /// 分页获取数据列表
  1006. /// </summary>
  1007. /// <param name="strWhere">筛选条件</param>
  1008. /// <param name="orderby">排序</param>
  1009. /// <param name="pageIndex">当前页</param>
  1010. /// <param name="pageSize">页面大小,每页显示条数</param>
  1011. /// <param name="pageCount">返回总页数</param>
  1012. /// <returns></returns>
  1013. public DataSet GetListByPage(string strWhere, string orderby, int pageIndex, int pageSize, ref int pageCount)
  1014. {
  1015. pageCount = GetByPageCount(strWhere, pageSize);
  1016. return this.GetListByPage(strWhere, orderby, (pageIndex - 1) * pageSize, pageIndex * pageSize);
  1017. }
  1018. /// <summary>
  1019. /// 分页获取数据列表
  1020. /// </summary>
  1021. /// <param name="strWhere">条件</param>
  1022. /// <param name="orderby">排序</param>
  1023. /// <param name="startIndex">开始index</param>
  1024. /// <param name="endIndex">结束index</param>
  1025. /// <returns></returns>
  1026. public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
  1027. {
  1028. if (!string.IsNullOrEmpty(strWhere.Trim()))
  1029. {
  1030. strWhere = " Where " + strWhere;
  1031. }
  1032. if (!string.IsNullOrEmpty(orderby.Trim()))
  1033. {
  1034. orderby = " Order By " + orderby;
  1035. }
  1036. StringBuilder strSql = new StringBuilder();
  1037. strSql.Append("SELECT * FROM " + this.TableName + " Where ID Not IN ");
  1038. strSql.Append("(Select Top " + startIndex + " ID From " + this.TableName + " " + strWhere + orderby + ")");
  1039. strSql.Append(" And ID In ");
  1040. strSql.Append("(Select Top " + endIndex + " ID From " + this.TableName + " " + strWhere + orderby + ")");
  1041. strSql.Append(orderby);
  1042. DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
  1043. ds.Tables[0].TableName = this.TableName;
  1044. return ds;
  1045. }
  1046. #endregion
  1047. #region 杨云奕添加 17-04-09 优化sql新增修改的方法
  1048. /// <summary>
  1049. /// 通过泛型实体生成更新语句和对象
  1050. /// </summary>
  1051. /// <typeparam name="T"></typeparam>
  1052. /// <param name="date"></param>
  1053. /// <param name="filterFieldName"></param>
  1054. /// <param name="operators"></param>
  1055. /// <param name="overlookFieldList"></param>
  1056. /// <param name="whereStr"></param>
  1057. /// <param name="type"></param>
  1058. /// <returns></returns>
  1059. public LYFZ.Helper.CommandInfo GetUpdateCommandInfoByEntity(T date, string filterFieldName = "ID",
  1060. string operators = "=", string overlookFieldList = "ID", string whereStr = null,
  1061. EffentNextType type = EffentNextType.None)
  1062. {
  1063. var properties = ReflectionHelper.GetProperties(typeof(T));
  1064. StringBuilder strSql = new StringBuilder();
  1065. Dictionary<string, PropertyInfo> dicWhereData = new Dictionary<string, PropertyInfo>();
  1066. strSql.Append("update " + this.TableName + " set ");
  1067. List<SqlParameter> parameterlist = new List<SqlParameter>();
  1068. var ignorePropertyNames = new HashSet<string>();
  1069. var filterPropertyNames = new HashSet<string>();
  1070. ///跳过的字段数据
  1071. if (!string.IsNullOrEmpty(overlookFieldList))
  1072. {
  1073. foreach (var msg in overlookFieldList.Split(','))
  1074. {
  1075. ignorePropertyNames.Add(msg);
  1076. }
  1077. }
  1078. ///用于查询的where条件的数据
  1079. if (!string.IsNullOrEmpty(filterFieldName))
  1080. {
  1081. foreach (var msg in filterFieldName.Split(','))
  1082. {
  1083. filterPropertyNames.Add(msg);
  1084. }
  1085. }
  1086. foreach (var property in properties)
  1087. {
  1088. var ignoreProperty = ignorePropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
  1089. var filterProperty = filterPropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
  1090. if (filterProperty != null)
  1091. {
  1092. dicWhereData.Add(property.Key, property.Value);
  1093. }
  1094. if (ignoreProperty != null)
  1095. continue;
  1096. var propertyType = ReflectionHelper.GetPropertyType(property.Value);
  1097. if( propertyType.Name.ToLower().IndexOf("list")!=-1)
  1098. {
  1099. continue;
  1100. }
  1101. var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
  1102. if (propertyValue == null)
  1103. {
  1104. continue;
  1105. }
  1106. else if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && propertyValue.ToString().Contains("0001"))
  1107. {
  1108. continue;
  1109. }
  1110. else if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && Convert.ToDateTime(propertyValue) <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
  1111. {
  1112. continue;
  1113. }
  1114. // ColumnAction(property.Value.Name, propertyValue, propertyType, DataTypes.Object, 0);
  1115. if (propertyValue != null)
  1116. {
  1117. strSql.Append("" + property.Key + "=@" + property.Key + ",");
  1118. SqlParameter parameter = new SqlParameter("@" + property.Key, propertyValue);
  1119. parameterlist.Add(parameter);
  1120. }
  1121. }
  1122. //去除结尾多余的“,”
  1123. if (strSql.ToString().LastIndexOf(',') == strSql.Length - 1)
  1124. {
  1125. strSql.Remove(strSql.Length - 1, 1);
  1126. }
  1127. if (whereStr == null)
  1128. {
  1129. if (filterFieldName != "" && operators != "")
  1130. {
  1131. string strWhere = "";
  1132. foreach (var property in dicWhereData)
  1133. {
  1134. if (!string.IsNullOrEmpty(strWhere))
  1135. {
  1136. strWhere += " and ";
  1137. }
  1138. strWhere += property.Key + operators + "@" + property.Key;
  1139. var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
  1140. parameterlist.Add(new SqlParameter("@" + property.Key, propertyValue));
  1141. }
  1142. strSql.Append(" where " + strWhere);
  1143. }
  1144. }
  1145. else
  1146. {
  1147. strSql.Append(" where 1=1 and (" + whereStr + ")");
  1148. }
  1149. SqlParameter[] parameters = parameterlist.ToArray();
  1150. return new CommandInfo(strSql.ToString(), parameters, type);
  1151. }
  1152. /// <summary>
  1153. /// 通过泛型方法生成新增对象信息
  1154. /// </summary>
  1155. /// <typeparam name="T"></typeparam>
  1156. /// <param name="date"></param>
  1157. /// <param name="overlookFieldList"></param>
  1158. /// <param name="type"></param>
  1159. /// <returns></returns>
  1160. public LYFZ.Helper.CommandInfo GetAddCommandInfoByEntity(T date,
  1161. string overlookFieldList = "ID",
  1162. EffentNextType type = EffentNextType.None)
  1163. {
  1164. StringBuilder strSql = new StringBuilder();
  1165. var properties = ReflectionHelper.GetProperties(typeof(T));
  1166. StringBuilder tempFieldNameString = new StringBuilder();
  1167. StringBuilder tempValueVariable = new StringBuilder();
  1168. List<SqlParameter> parameterlist = new List<SqlParameter>();
  1169. var ignorePropertyNames = new HashSet<string>();
  1170. if (!string.IsNullOrEmpty(overlookFieldList))
  1171. {
  1172. foreach (var msg in overlookFieldList.Split(','))
  1173. {
  1174. ignorePropertyNames.Add(msg);
  1175. }
  1176. }
  1177. foreach (var property in properties)
  1178. {
  1179. var ignoreProperty = ignorePropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
  1180. if (ignoreProperty != null)
  1181. continue;
  1182. var propertyType = ReflectionHelper.GetPropertyType(property.Value);
  1183. if (propertyType.Name.ToLower().IndexOf("list") != -1)
  1184. {
  1185. continue;
  1186. }
  1187. var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
  1188. if (propertyValue==null)
  1189. {
  1190. continue;
  1191. }
  1192. if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && propertyValue.ToString().Contains("0001"))
  1193. {
  1194. continue;
  1195. }
  1196. if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && Convert.ToDateTime(propertyValue) <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
  1197. {
  1198. continue;
  1199. }
  1200. else if (property.Key.ToLower() == "id" && propertyType == typeof(long) && (propertyValue == null || Convert.ToInt64(propertyValue) == 0))
  1201. {
  1202. propertyValue = LYFZ.WinAPI.CustomPublicMethod.GenerateId();
  1203. }
  1204. if (propertyValue != null)
  1205. {
  1206. tempFieldNameString.Append("" + property.Key + ",");
  1207. tempValueVariable.Append("@" + property.Key + ",");
  1208. SqlParameter parameter = new SqlParameter("@" + property.Key, propertyValue);
  1209. parameterlist.Add(parameter);
  1210. }
  1211. }
  1212. if (tempFieldNameString.ToString().LastIndexOf(',') == tempFieldNameString.Length - 1)
  1213. {
  1214. tempFieldNameString.Remove(tempFieldNameString.Length - 1, 1);
  1215. }
  1216. //去除结尾多余的“,”
  1217. if (tempValueVariable.ToString().LastIndexOf(',') == tempValueVariable.Length - 1)
  1218. {
  1219. tempValueVariable.Remove(tempValueVariable.Length - 1, 1);
  1220. }
  1221. strSql.Append("insert into " + this.TableName + "(");
  1222. strSql.Append("" + tempFieldNameString.ToString() + ")");
  1223. strSql.Append(" values (");
  1224. strSql.Append("" + tempValueVariable.ToString() + ")");
  1225. strSql.Append(";select @@IDENTITY");
  1226. SqlParameter[] parameters = parameterlist.ToArray();
  1227. return new CommandInfo(strSql.ToString(), parameters, type);
  1228. }
  1229. public object GetAddCommandInfoByEntity(T date, string overlookFieldList = "ID")
  1230. {
  1231. return GetAddCommandInfoByEntity(date, overlookFieldList, EffentNextType.None);
  1232. }
  1233. public object GetUpdateCommandInfoByEntity(T date, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
  1234. {
  1235. return GetUpdateCommandInfoByEntity(date, filterFieldName, operators, overlookFieldList, whereStr, EffentNextType.None);
  1236. }
  1237. #endregion
  1238. /// <summary>
  1239. /// 转Json数据为Model
  1240. /// </summary>
  1241. /// <typeparam name="T"></typeparam>
  1242. /// <param name="json"></param>
  1243. /// <returns></returns>
  1244. public static T JsonToModelByEntity(string json)
  1245. {
  1246. T t = Activator.CreateInstance<T>();
  1247. T obj = (T)Newtonsoft.Json.JsonConvert.DeserializeObject(json, t.GetType());
  1248. return obj;
  1249. }
  1250. /// <summary>
  1251. /// 分页查询记录
  1252. /// </summary>
  1253. /// <returns></returns>
  1254. public DataSet PagingQueryDataTable(string _pageTableName, string _QueryFieldName, string _OrderStr, string _QueryCondition, int _PageSize, int _PageIndex, out int _TotalCount)
  1255. {
  1256. SqlParameter[] parameters = {
  1257. new SqlParameter("@TableName", SqlDbType.VarChar , 2000),
  1258. new SqlParameter("@ReFieldsStr" , SqlDbType.VarChar , 2000),
  1259. new SqlParameter("@OrderString", SqlDbType.VarChar , 2000 ),
  1260. new SqlParameter("@WhereString", SqlDbType.VarChar, 2000),
  1261. new SqlParameter("@PageSize", SqlDbType.Int),
  1262. new SqlParameter("@PageIndex", SqlDbType.Int),
  1263. new SqlParameter("@TotalRecord", SqlDbType.Int)
  1264. };
  1265. parameters[0].Value = _pageTableName;
  1266. parameters[1].Value = _QueryFieldName;
  1267. parameters[2].Value = _OrderStr;
  1268. parameters[3].Value = _QueryCondition;
  1269. parameters[4].Value = _PageSize;
  1270. parameters[5].Value = _PageIndex;
  1271. parameters[6].Direction = ParameterDirection.Output;
  1272. DataSet ds = LYFZ.Helper.SQLHelper.RunProcedure("PROCE_SQL2005PAGECHANGE", parameters, _pageTableName + "_ds",this._DBConn.GetDBConnectionString());
  1273. _TotalCount = Convert.ToInt32(parameters[6].Value);
  1274. //if (_TotalCount == 0)
  1275. //{
  1276. // _PageCount = 0;
  1277. //}
  1278. //else
  1279. //{
  1280. // _PageCount = _TotalCount % _PageSize == 0 ? _TotalCount / _PageSize : _TotalCount / _PageSize + 1;
  1281. //}
  1282. return ds;
  1283. }
  1284. }
  1285. #region 杨云奕添加 17-04-09 反射助手,用于泛型实体的反射操作
  1286. internal static class ReflectionHelper
  1287. {
  1288. private static readonly ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> _cachedProperties = new ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>>();
  1289. /// <summary>
  1290. /// 得到实体反射的表达式
  1291. /// </summary>
  1292. /// <typeparam name="T"></typeparam>
  1293. /// <param name="expression"></param>
  1294. /// <returns></returns>
  1295. public static string GetPropertyNameFromExpression<T>(Expression<Func<T, object>> expression)
  1296. {
  1297. string propertyPath = null;
  1298. if (expression.Body is UnaryExpression)
  1299. {
  1300. var unaryExpression = (UnaryExpression)expression.Body;
  1301. if (unaryExpression.NodeType == ExpressionType.Convert)
  1302. propertyPath = unaryExpression.Operand.ToString();
  1303. }
  1304. if (propertyPath == null)
  1305. propertyPath = expression.Body.ToString();
  1306. propertyPath = propertyPath.Replace(expression.Parameters[0] + ".", string.Empty);
  1307. return propertyPath;
  1308. }
  1309. public static List<string> GetPropertyNamesFromExpressions<T>(Expression<Func<T, object>>[] expressions)
  1310. {
  1311. var propertyNames = new List<string>();
  1312. foreach (var expression in expressions)
  1313. {
  1314. var propertyName = GetPropertyNameFromExpression(expression);
  1315. propertyNames.Add(propertyName);
  1316. }
  1317. return propertyNames;
  1318. }
  1319. public static object GetPropertyValue(object item, PropertyInfo property)
  1320. {
  1321. var value = property.GetValue(item, null);
  1322. return value;
  1323. }
  1324. public static object GetPropertyValue(object item, string propertyName)
  1325. {
  1326. PropertyInfo property;
  1327. foreach (var part in propertyName.Split('.'))
  1328. {
  1329. if (item == null)
  1330. return null;
  1331. var type = item.GetType();
  1332. property = type.GetProperty(part);
  1333. if (property == null)
  1334. return null;
  1335. item = GetPropertyValue(item, property);
  1336. }
  1337. return item;
  1338. }
  1339. public static object GetPropertyValueDynamic(object item, string name)
  1340. {
  1341. var dictionary = (IDictionary<string, object>)item;
  1342. return dictionary[name];
  1343. }
  1344. public static Dictionary<string, PropertyInfo> GetProperties(Type type)
  1345. {
  1346. var properties = _cachedProperties.GetOrAdd(type, BuildPropertyDictionary);
  1347. return properties;
  1348. }
  1349. private static Dictionary<string, PropertyInfo> BuildPropertyDictionary(Type type)
  1350. {
  1351. var result = new Dictionary<string, PropertyInfo>();
  1352. var properties = type.GetProperties();
  1353. foreach (var property in properties)
  1354. {
  1355. result.Add(property.Name.ToLower(), property);
  1356. }
  1357. return result;
  1358. }
  1359. public static bool IsList(object item)
  1360. {
  1361. if (item is ICollection)
  1362. return true;
  1363. return false;
  1364. }
  1365. public static bool IsNullable(PropertyInfo property)
  1366. {
  1367. if (property.PropertyType.IsGenericType &&
  1368. property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  1369. return true;
  1370. return false;
  1371. }
  1372. /// <summary>
  1373. /// Includes a work around for getting the actual type of a Nullable type.
  1374. /// </summary>
  1375. public static Type GetPropertyType(PropertyInfo property)
  1376. {
  1377. if (IsNullable(property))
  1378. return property.PropertyType.GetGenericArguments()[0];
  1379. return property.PropertyType;
  1380. }
  1381. public static object GetDefault(Type type)
  1382. {
  1383. if (type.IsValueType)
  1384. return Activator.CreateInstance(type);
  1385. return null;
  1386. }
  1387. public static bool IsBasicClrType(Type type)
  1388. {
  1389. if (type.IsEnum
  1390. || type.IsPrimitive
  1391. || type.IsValueType
  1392. || type == typeof(string)
  1393. || type == typeof(DateTime))
  1394. return true;
  1395. return false;
  1396. }
  1397. public static bool IsCustomEntity<T>()
  1398. {
  1399. var type = typeof(T);
  1400. if (type.IsClass && Type.GetTypeCode(type) == TypeCode.Object)
  1401. return true;
  1402. return false;
  1403. }
  1404. }
  1405. #endregion
  1406. }