BaseDAL.cs 68 KB

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