InsertableHelper.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. namespace SqlSugar
  11. {
  12. public partial class InsertableProvider<T> : IInsertable<T> where T : class, new()
  13. {
  14. #region Protected Methods
  15. private string _ExecuteReturnBigIdentity()
  16. {
  17. InsertBuilder.IsReturnIdentity = true;
  18. PreToSql();
  19. AutoRemoveDataCache();
  20. string sql = InsertBuilder.ToSqlString();
  21. RestoreMapping();
  22. Before(sql);
  23. return sql;
  24. }
  25. private string _ExecuteReturnIdentity()
  26. {
  27. InsertBuilder.IsReturnIdentity = true;
  28. PreToSql();
  29. AutoRemoveDataCache();
  30. string sql = InsertBuilder.ToSqlString();
  31. RestoreMapping();
  32. Before(sql);
  33. return sql;
  34. }
  35. private string _ExecuteCommand()
  36. {
  37. if (InsertBuilder.DbColumnInfoList.HasValue())
  38. {
  39. var pks = GetPrimaryKeys();
  40. foreach (var item in InsertBuilder.DbColumnInfoList)
  41. {
  42. var isPk = pks.Any(y => y.Equals(item.DbColumnName, StringComparison.CurrentCultureIgnoreCase)) || item.IsPrimarykey;
  43. if (isPk && item.PropertyType == UtilConstants.GuidType && item.Value.ObjToString() == Guid.Empty.ToString())
  44. {
  45. if (StaticConfig.CustomGuidFunc != null)
  46. {
  47. item.Value = StaticConfig.CustomGuidFunc();
  48. }
  49. else
  50. {
  51. item.Value = Guid.NewGuid();
  52. }
  53. if (InsertObjs.First().GetType().GetProperties().Any(it => it.Name == item.PropertyName))
  54. InsertObjs.First().GetType().GetProperties().First(it => it.Name == item.PropertyName).SetValue(InsertObjs.First(), item.Value, null);
  55. }
  56. }
  57. }
  58. InsertBuilder.IsReturnIdentity = false;
  59. PreToSql();
  60. AutoRemoveDataCache();
  61. string sql = InsertBuilder.ToSqlString();
  62. RestoreMapping();
  63. Before(sql);
  64. return sql;
  65. }
  66. private void AutoRemoveDataCache()
  67. {
  68. var moreSetts = this.Context.CurrentConnectionConfig.MoreSettings;
  69. var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices;
  70. if (moreSetts != null && moreSetts.IsAutoRemoveDataCache && extService != null && extService.DataInfoCacheService != null)
  71. {
  72. this.RemoveDataCache();
  73. }
  74. }
  75. protected virtual void PreToSql()
  76. {
  77. #region Identities
  78. if (!IsOffIdentity)
  79. {
  80. List<string> identities = GetIdentityKeys();
  81. if (identities != null && identities.Any())
  82. {
  83. this.InsertBuilder.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList.Where(it =>
  84. {
  85. return !identities.Any(i => it.DbColumnName.Equals(i, StringComparison.CurrentCultureIgnoreCase));
  86. }).ToList();
  87. }
  88. }
  89. #endregion
  90. #region IgnoreColumns
  91. if (this.Context.IgnoreColumns != null && this.Context.IgnoreColumns.Any())
  92. {
  93. var currentIgnoreColumns = this.Context.IgnoreColumns.Where(it => it.EntityName == this.EntityInfo.EntityName).ToList();
  94. this.InsertBuilder.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList.Where(it =>
  95. {
  96. return !currentIgnoreColumns.Any(i => it.PropertyName.Equals(i.PropertyName, StringComparison.CurrentCulture));
  97. }).ToList();
  98. }
  99. if (this.Context.IgnoreInsertColumns != null && this.Context.IgnoreInsertColumns.Any())
  100. {
  101. var currentIgnoreColumns = this.Context.IgnoreInsertColumns.Where(it => it.EntityName == this.EntityInfo.EntityName).ToList();
  102. this.InsertBuilder.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList.Where(it =>
  103. {
  104. return !currentIgnoreColumns.Any(i => it.PropertyName.Equals(i.PropertyName, StringComparison.CurrentCulture));
  105. }).ToList();
  106. }
  107. #endregion
  108. if (this.IsSingle)
  109. {
  110. var isDic = this.EntityInfo.DbTableName.StartsWith("Dictionary`");
  111. foreach (var item in this.InsertBuilder.DbColumnInfoList)
  112. {
  113. if (this.InsertBuilder.Parameters == null) this.InsertBuilder.Parameters = new List<SugarParameter>();
  114. var paramters = new SugarParameter(this.SqlBuilder.SqlParameterKeyWord + item.DbColumnName, item.Value, item.PropertyType);
  115. if (InsertBuilder.IsNoInsertNull && paramters.Value == null)
  116. {
  117. continue;
  118. }
  119. if (item.SqlParameterDbType is Type)
  120. {
  121. continue;
  122. }
  123. if (item.IsJson)
  124. {
  125. paramters.IsJson = true;
  126. SqlBuilder.ChangeJsonType(paramters);
  127. }
  128. if (item.IsArray)
  129. {
  130. paramters.IsArray = true;
  131. if (item.Value == null || item.Value == DBNull.Value)
  132. {
  133. ArrayNull(item,paramters);
  134. }
  135. }
  136. if (item.Value == null && isDic)
  137. {
  138. var type = this.SqlBuilder.GetNullType(this.InsertBuilder.GetTableNameString, item.DbColumnName);
  139. if (type != null)
  140. {
  141. paramters = new SugarParameter(this.SqlBuilder.SqlParameterKeyWord + item.DbColumnName, item.Value, type);
  142. }
  143. }
  144. this.InsertBuilder.Parameters.Add(paramters);
  145. }
  146. }
  147. }
  148. private static void ArrayNull(DbColumnInfo item, SugarParameter parameter)
  149. {
  150. if (item.PropertyType.IsIn(typeof(Guid[]), typeof(Guid?[])))
  151. {
  152. parameter.DbType = System.Data.DbType.Guid;
  153. }
  154. else if (item.PropertyType.IsIn(typeof(int[]), typeof(int?[])))
  155. {
  156. parameter.DbType = System.Data.DbType.Int32;
  157. }
  158. else if (item.PropertyType.IsIn(typeof(long[]), typeof(long?[])))
  159. {
  160. parameter.DbType = System.Data.DbType.Int64;
  161. }
  162. else if (item.PropertyType.IsIn(typeof(short[]), typeof(short?[])))
  163. {
  164. parameter.DbType = System.Data.DbType.Int16;
  165. }
  166. }
  167. internal void Init()
  168. {
  169. InsertBuilder.EntityInfo = this.EntityInfo;
  170. Check.Exception(InsertObjs == null || InsertObjs.Count() == 0, "InsertObjs is null");
  171. int i = 0;
  172. foreach (var item in InsertObjs)
  173. {
  174. List<DbColumnInfo> insertItem = new List<DbColumnInfo>();
  175. if (item is Dictionary<string, string>)
  176. {
  177. Check.ExceptionEasy("To use Insertable dictionary, use string or object", "Insertable字典请使用string,object类型");
  178. }
  179. if (item is Dictionary<string, object>)
  180. {
  181. SetInsertItemByDic(i, item, insertItem);
  182. }
  183. else
  184. {
  185. DataAop(item);
  186. SetInsertItemByEntity(i, item, insertItem);
  187. }
  188. this.InsertBuilder.DbColumnInfoList.AddRange(insertItem);
  189. ++i;
  190. }
  191. }
  192. private void DataAop(T item)
  193. {
  194. var dataEvent = this.Context.CurrentConnectionConfig.AopEvents?.DataExecuting;
  195. if (dataEvent != null && item != null)
  196. {
  197. foreach (var columnInfo in this.EntityInfo.Columns)
  198. {
  199. dataEvent(columnInfo.PropertyInfo.GetValue(item, null), new DataFilterModel() { OperationType = DataFilterType.InsertByObject, EntityValue = item, EntityColumnInfo = columnInfo });
  200. }
  201. }
  202. }
  203. private void SetInsertItemByDic(int i, T item, List<DbColumnInfo> insertItem)
  204. {
  205. foreach (var column in (item as Dictionary<string, object>).OrderBy(it=>it.Key))
  206. {
  207. var columnInfo = new DbColumnInfo()
  208. {
  209. Value = column.Value,
  210. DbColumnName = column.Key,
  211. PropertyName = column.Key,
  212. PropertyType = column.Value == null ? DBNull.Value.GetType() : UtilMethods.GetUnderType(column.Value.GetType()),
  213. TableId = i
  214. };
  215. if (columnInfo.PropertyType?.FullName == "System.Text.Json.JsonElement")
  216. {
  217. columnInfo.Value = column.Value.ObjToString();
  218. }
  219. if (columnInfo.PropertyType.IsEnum())
  220. {
  221. if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true)
  222. {
  223. columnInfo.Value = columnInfo.Value.ToString();
  224. columnInfo.PropertyType = UtilConstants.StringType;
  225. }
  226. else
  227. {
  228. columnInfo.Value = Convert.ToInt64(columnInfo.Value);
  229. }
  230. }
  231. insertItem.Add(columnInfo);
  232. }
  233. }
  234. private void SetInsertItemByEntity(int i, T item, List<DbColumnInfo> insertItem)
  235. {
  236. if (item == null)
  237. {
  238. return;
  239. }
  240. foreach (var column in EntityInfo.Columns)
  241. {
  242. if (column.IsIgnore || column.IsOnlyIgnoreInsert) continue;
  243. var isMapping = IsMappingColumns;
  244. var columnInfo = new DbColumnInfo()
  245. {
  246. Value = GetValue(item,column),
  247. DbColumnName = column.DbColumnName,
  248. PropertyName = column.PropertyName,
  249. PropertyType = UtilMethods.GetUnderType(column.PropertyInfo),
  250. TableId = i,
  251. InsertSql = column.InsertSql,
  252. InsertServerTime = column.InsertServerTime,
  253. DataType=column.DataType,
  254. SqlParameterDbType= column.SqlParameterDbType ,
  255. IsIdentity= column.IsIdentity
  256. };
  257. if (column.DbColumnName == null)
  258. {
  259. column.DbColumnName = column.PropertyName;
  260. }
  261. if (isMapping)
  262. {
  263. columnInfo.DbColumnName = GetDbColumnName(column.PropertyName);
  264. }
  265. if (column.IsJson)
  266. {
  267. columnInfo.IsJson = true;
  268. }
  269. if (column.IsArray)
  270. {
  271. columnInfo.IsArray = true;
  272. }
  273. if (columnInfo.PropertyType.IsEnum() && columnInfo.Value != null)
  274. {
  275. if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true)
  276. {
  277. columnInfo.Value = columnInfo.Value.ToString();
  278. columnInfo.PropertyType = UtilConstants.StringType;
  279. }
  280. else
  281. {
  282. columnInfo.Value = Convert.ToInt64(columnInfo.Value);
  283. }
  284. }
  285. if (column.IsJson && columnInfo.Value != null)
  286. {
  287. if (columnInfo.Value != null)
  288. columnInfo.Value = this.Context.Utilities.SerializeObject(columnInfo.Value);
  289. }
  290. //var tranColumn=EntityInfo.Columns.FirstOrDefault(it => it.IsTranscoding && it.DbColumnName.Equals(column.DbColumnName, StringComparison.CurrentCultureIgnoreCase));
  291. if (column.IsTranscoding && columnInfo.Value.HasValue())
  292. {
  293. columnInfo.Value = UtilMethods.EncodeBase64(columnInfo.Value.ToString());
  294. }
  295. insertItem.Add(columnInfo);
  296. }
  297. if (EntityInfo.Discrimator.HasValue())
  298. {
  299. Check.ExceptionEasy(!Regex.IsMatch(EntityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格");
  300. var array = EntityInfo.Discrimator.Split(',');
  301. foreach (var disItem in array)
  302. {
  303. var name = disItem.Split(':').First();
  304. var value = disItem.Split(':').Last();
  305. insertItem.Add(new DbColumnInfo() { DbColumnName = name, PropertyName = name, PropertyType = typeof(string), Value = value });
  306. }
  307. }
  308. }
  309. private static object GetValue(T item, EntityColumnInfo column)
  310. {
  311. if (column.ForOwnsOnePropertyInfo != null)
  312. {
  313. var owsPropertyValue= column.ForOwnsOnePropertyInfo.GetValue(item, null);
  314. return column.PropertyInfo.GetValue(owsPropertyValue, null);
  315. }
  316. if (StaticConfig.EnableAot)
  317. {
  318. return column.PropertyInfo.GetValue(item, null);
  319. }
  320. else
  321. {
  322. return PropertyCallAdapterProvider<T>.GetInstance(column.PropertyName).InvokeGet(item);
  323. }
  324. }
  325. private string GetDbColumnName(string propertyName)
  326. {
  327. if (!IsMappingColumns)
  328. {
  329. return propertyName;
  330. }
  331. if (this.Context.MappingColumns.Any(it => it.EntityName.Equals(EntityInfo.EntityName, StringComparison.CurrentCultureIgnoreCase)))
  332. {
  333. this.MappingColumnList = this.Context.MappingColumns.Where(it => it.EntityName.Equals(EntityInfo.EntityName, StringComparison.CurrentCultureIgnoreCase)).ToList();
  334. }
  335. if (MappingColumnList == null || !MappingColumnList.Any())
  336. {
  337. return propertyName;
  338. }
  339. else
  340. {
  341. var mappInfo = this.MappingColumnList.FirstOrDefault(it => it.PropertyName.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase));
  342. return mappInfo == null ? propertyName : mappInfo.DbColumnName;
  343. }
  344. }
  345. protected virtual List<string> GetPrimaryKeys()
  346. {
  347. if (this.Context.IsSystemTablesConfig)
  348. {
  349. return this.Context.DbMaintenance.GetPrimaries(this.Context.EntityMaintenance.GetTableName(this.EntityInfo.EntityName));
  350. }
  351. else
  352. {
  353. return this.EntityInfo.Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToList();
  354. }
  355. }
  356. protected virtual List<string> GetIdentityKeys()
  357. {
  358. if (this.Context.IsSystemTablesConfig)
  359. {
  360. return this.Context.DbMaintenance.GetIsIdentities(this.Context.EntityMaintenance.GetTableName(this.EntityInfo.EntityName));
  361. }
  362. else
  363. {
  364. return this.EntityInfo.Columns.Where(it => {
  365. if (StaticConfig.Check_StringIdentity)
  366. {
  367. Check.ExceptionEasy(it.IsIdentity && it.UnderType == typeof(string), "Auto-incremented is not a string, how can I use a executable startup configuration: StaticConfig.Check_StringIdentity=false ", "自增不是能string,如何非要用可以程序启动配置:StaticConfig.Check_StringIdentity=false");
  368. }
  369. return it.IsIdentity;
  370. }).Select(it => it.DbColumnName).ToList();
  371. }
  372. }
  373. //private void TaskStart<Type>(Task<Type> result)
  374. //{
  375. // if (this.Context.CurrentConnectionConfig.IsShardSameThread)
  376. // {
  377. // Check.Exception(true, "IsShardSameThread=true can't be used async method");
  378. // }
  379. // result.Start();
  380. //}
  381. protected void RestoreMapping()
  382. {
  383. if (IsAs)
  384. {
  385. this.Context.MappingTables = OldMappingTableList;
  386. }
  387. }
  388. //protected IInsertable<T> CopyInsertable()
  389. //{
  390. // var asyncContext = this.Context.Utilities.CopyContext(true);
  391. // asyncContext.CurrentConnectionConfig.IsAutoCloseConnection = true;
  392. // asyncContext.IsAsyncMethod = true;
  393. // var asyncInsertable = asyncContext.Insertable<T>(this.InsertObjs);
  394. // var asyncInsertableBuilder = asyncInsertable.InsertBuilder;
  395. // asyncInsertableBuilder.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList;
  396. // asyncInsertableBuilder.EntityInfo = this.InsertBuilder.EntityInfo;
  397. // asyncInsertableBuilder.Parameters = this.InsertBuilder.Parameters;
  398. // asyncInsertableBuilder.sql = this.InsertBuilder.sql;
  399. // asyncInsertableBuilder.IsNoInsertNull = this.InsertBuilder.IsNoInsertNull;
  400. // asyncInsertableBuilder.IsReturnIdentity = this.InsertBuilder.IsReturnIdentity;
  401. // asyncInsertableBuilder.EntityInfo = this.InsertBuilder.EntityInfo;
  402. // asyncInsertableBuilder.TableWithString = this.InsertBuilder.TableWithString;
  403. // if (this.RemoveCacheFunc != null)
  404. // {
  405. // asyncInsertable.RemoveDataCache();
  406. // }
  407. // return asyncInsertable;
  408. //}
  409. protected void After(string sql, long? result)
  410. {
  411. if (this.IsEnableDiffLogEvent)
  412. {
  413. var isDisableMasterSlaveSeparation = this.Ado.IsDisableMasterSlaveSeparation;
  414. this.Ado.IsDisableMasterSlaveSeparation = true;
  415. var parameters = InsertBuilder.Parameters;
  416. if (parameters == null)
  417. parameters = new List<SugarParameter>();
  418. diffModel.AfterData = GetDiffTable(sql, result);
  419. diffModel.Time = this.Context.Ado.SqlExecutionTime;
  420. if (this.Context.CurrentConnectionConfig.AopEvents.OnDiffLogEvent != null)
  421. this.Context.CurrentConnectionConfig.AopEvents.OnDiffLogEvent(diffModel);
  422. this.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation;
  423. }
  424. if (this.RemoveCacheFunc != null)
  425. {
  426. this.RemoveCacheFunc();
  427. }
  428. }
  429. protected void Before(string sql)
  430. {
  431. if (this.IsEnableDiffLogEvent)
  432. {
  433. var isDisableMasterSlaveSeparation = this.Ado.IsDisableMasterSlaveSeparation;
  434. this.Ado.IsDisableMasterSlaveSeparation = true;
  435. var parameters = InsertBuilder.Parameters;
  436. if (parameters == null)
  437. parameters = new List<SugarParameter>();
  438. diffModel.BeforeData = null;
  439. diffModel.Sql = sql;
  440. diffModel.Parameters = parameters.ToArray();
  441. this.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation;
  442. }
  443. }
  444. private List<DiffLogTableInfo> GetDiffTable(string sql, long? identity)
  445. {
  446. if (GetIdentityKeys().HasValue() && this.InsertObjs.Count() > 1)
  447. {
  448. return GetDiffTableByEntity();
  449. }
  450. else if (GetIdentityKeys().IsNullOrEmpty())
  451. {
  452. return GetDiffTableByEntity();
  453. }
  454. else
  455. {
  456. return GetDiffTableBySql(identity);
  457. }
  458. }
  459. private List<DiffLogTableInfo> GetDiffTableByEntity()
  460. {
  461. List<SugarParameter> parameters = new List<SugarParameter>();
  462. List<DiffLogTableInfo> result = new List<DiffLogTableInfo>();
  463. var dt2 = this.Context.Utilities.ListToDataTable<T>(this.InsertObjs.ToList());
  464. foreach (DataRow row in dt2.Rows)
  465. {
  466. DiffLogTableInfo item = new DiffLogTableInfo();
  467. item.TableDescription = this.EntityInfo.TableDescription;
  468. item.TableName = this.EntityInfo.DbTableName;
  469. item.Columns = new List<DiffLogColumnInfo>();
  470. foreach (DataColumn col in dt2.Columns)
  471. {
  472. var sugarColumn = this.EntityInfo.Columns.Where(it => it.DbColumnName != null).FirstOrDefault(it =>
  473. it.PropertyName.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase));
  474. DiffLogColumnInfo addItem = new DiffLogColumnInfo();
  475. addItem.Value = row[col.ColumnName];
  476. addItem.ColumnName = sugarColumn?.DbColumnName??col.ColumnName;
  477. addItem.IsPrimaryKey = sugarColumn?.IsPrimarykey ?? false;
  478. addItem.ColumnDescription = sugarColumn?.ColumnDescription;
  479. item.Columns.Add(addItem);
  480. }
  481. result.Add(item);
  482. }
  483. return result;
  484. }
  485. private List<DiffLogTableInfo> GetDiffTableBySql(long? identity)
  486. {
  487. List<SugarParameter> parameters = new List<SugarParameter>();
  488. List<DiffLogTableInfo> result = new List<DiffLogTableInfo>();
  489. var whereSql = string.Empty;
  490. List<IConditionalModel> cons = new List<IConditionalModel>();
  491. if (identity != null && identity > 0 && GetIdentityKeys().HasValue())
  492. {
  493. var fieldName = GetIdentityKeys().Last();
  494. if (this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL)
  495. {
  496. var fieldObjectType = this.EntityInfo.Columns.FirstOrDefault(x => x.DbColumnName == fieldName)
  497. .PropertyInfo.PropertyType;
  498. cons.Add(new ConditionalModel()
  499. {
  500. ConditionalType = ConditionalType.Equal,
  501. FieldName = fieldName,
  502. FieldValue = identity.ToString(),
  503. FieldValueConvertFunc = it => UtilMethods.ChangeType2(it, fieldObjectType)
  504. });
  505. }
  506. else
  507. cons.Add(new ConditionalModel() { ConditionalType = ConditionalType.Equal, FieldName = fieldName, FieldValue = identity.ToString() });
  508. }
  509. else
  510. {
  511. foreach (var item in this.EntityInfo.Columns.Where(it => it.IsIgnore == false && GetPrimaryKeys().Any(pk => pk.Equals(it.DbColumnName, StringComparison.CurrentCultureIgnoreCase))))
  512. {
  513. var fielddName = item.DbColumnName;
  514. var filedObject = this.EntityInfo.Columns.FirstOrDefault(it => it.PropertyName == item.PropertyName).PropertyInfo.GetValue(this.InsertObjs.Last(), null);
  515. var fieldValue = filedObject.ObjToString();
  516. if (filedObject != null && filedObject.GetType() != typeof(string) && this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL)
  517. {
  518. cons.Add(new ConditionalModel() { ConditionalType = ConditionalType.Equal, FieldName = fielddName, FieldValue = fieldValue, FieldValueConvertFunc = it => UtilMethods.ChangeType2(it, filedObject.GetType()) });
  519. }
  520. else
  521. {
  522. cons.Add(new ConditionalModel() { ConditionalType = ConditionalType.Equal, FieldName = fielddName, FieldValue = fieldValue });
  523. }
  524. }
  525. }
  526. Check.Exception(cons.IsNullOrEmpty(), "Insertable.EnableDiffLogEvent need primary key");
  527. var sqlable = this.SqlBuilder.ConditionalModelToSql(cons);
  528. whereSql = sqlable.Key;
  529. parameters.AddRange(sqlable.Value);
  530. var dt = this.Context.Queryable<T>().Where(whereSql).AddParameters(parameters).ToDataTable();
  531. if (dt.Rows != null && dt.Rows.Count > 0)
  532. {
  533. foreach (DataRow row in dt.Rows)
  534. {
  535. DiffLogTableInfo item = new DiffLogTableInfo();
  536. item.TableDescription = this.EntityInfo.TableDescription;
  537. item.TableName = this.EntityInfo.DbTableName;
  538. item.Columns = new List<DiffLogColumnInfo>();
  539. foreach (DataColumn col in dt.Columns)
  540. {
  541. var sugarColumn = this.EntityInfo.Columns.Where(it => it.DbColumnName != null).First(it =>
  542. it.DbColumnName.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase));
  543. DiffLogColumnInfo addItem = new DiffLogColumnInfo();
  544. addItem.Value = row[col.ColumnName];
  545. addItem.ColumnName = col.ColumnName;
  546. addItem.IsPrimaryKey = sugarColumn.IsPrimarykey;
  547. addItem.ColumnDescription = sugarColumn.ColumnDescription;
  548. item.Columns.Add(addItem);
  549. }
  550. result.Add(item);
  551. }
  552. return result;
  553. }
  554. else
  555. {
  556. DiffLogTableInfo diffTable = new DiffLogTableInfo();
  557. diffTable.TableName = this.EntityInfo.DbTableName;
  558. diffTable.TableDescription = this.EntityInfo.TableDescription;
  559. diffTable.Columns = this.EntityInfo.Columns.Where(it => it.IsIgnore == false).Select(it => new DiffLogColumnInfo()
  560. {
  561. ColumnDescription = it.ColumnDescription,
  562. ColumnName = it.DbColumnName,
  563. Value = it.PropertyInfo.GetValue(this.InsertObjs.Last(), null),
  564. IsPrimaryKey = it.IsPrimarykey
  565. }).ToList();
  566. return new List<DiffLogTableInfo>() { diffTable };
  567. }
  568. }
  569. public IInsertable<T> CallEntityMethod(Expression<Action<T>> method)
  570. {
  571. if (this.InsertObjs.HasValue())
  572. {
  573. var oldColumns = this.InsertBuilder.DbColumnInfoList.Select(it => it.PropertyName).ToList();
  574. var expression = (LambdaExpression.Lambda(method).Body as LambdaExpression).Body;
  575. Check.Exception(!(expression is MethodCallExpression), method.ToString() + " is not method");
  576. var callExpresion = expression as MethodCallExpression;
  577. UtilMethods.DataInoveByExpresson(this.InsertObjs, callExpresion);
  578. this.InsertBuilder.DbColumnInfoList = new List<DbColumnInfo>();
  579. Init();
  580. this.InsertBuilder.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList.Where(it => oldColumns.Contains(it.PropertyName)).ToList();
  581. }
  582. return this;
  583. }
  584. #endregion
  585. #region Insert PkList
  586. private List<Type> InsertPkListWithFunc<Type>(EntityColumnInfo pkInfo)
  587. {
  588. InsertBuilder.IsReturnPkList = true;
  589. InsertBuilder.IsNoPage = true;
  590. string sql = _ExecuteCommand();
  591. sql = this.InsertBuilder.ConvertInsertReturnIdFunc(SqlBuilder.GetTranslationColumnName(pkInfo.DbColumnName), sql);
  592. var result = Ado.SqlQuery<Type>(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray());
  593. After(sql, null);
  594. return result;
  595. }
  596. private List<Type> InsertPkListNoFunc<Type>(EntityColumnInfo pkInfo)
  597. {
  598. if (this.Ado.Transaction != null)
  599. {
  600. return ReturnDefaultIdentity<Type>(pkInfo);
  601. }
  602. else
  603. {
  604. try
  605. {
  606. this.Context.Ado.BeginTran();
  607. var result = ReturnDefaultIdentity<Type>(pkInfo);
  608. this.Context.Ado.CommitTran();
  609. return result;
  610. }
  611. catch (Exception ex)
  612. {
  613. this.Context.Ado.RollbackTran();
  614. throw ex;
  615. }
  616. }
  617. }
  618. private List<Type> InsertPkListIdentityCount1<Type>(EntityColumnInfo pkInfo)
  619. {
  620. if (pkInfo.UnderType == UtilConstants.IntType)
  621. {
  622. return new List<Type> { (Type)(object)this.ExecuteReturnIdentity() };
  623. }
  624. else
  625. {
  626. return new List<Type> { (Type)(object)this.ExecuteReturnBigIdentity() };
  627. }
  628. }
  629. private List<Type> InsertPkListLong<Type>()
  630. {
  631. var list = this.ExecuteReturnSnowflakeIdList();
  632. try
  633. {
  634. return list.Cast<Type>().ToList();
  635. }
  636. catch
  637. {
  638. Check.ExceptionEasy($"long to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" long 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败");
  639. return null;
  640. }
  641. }
  642. private List<Type> InsertPkListGuid<Type>(EntityColumnInfo pkInfo)
  643. {
  644. Check.ExceptionEasy(pkInfo.UnderType.Name != typeof(Type).Name, $"{pkInfo.UnderType.Name} to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" {pkInfo.UnderType.Name} 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败");
  645. this.ExecuteCommand();
  646. List<Type> result = new List<Type>();
  647. if (InsertBuilder.DbColumnInfoList.HasValue())
  648. {
  649. foreach (var item in InsertBuilder.DbColumnInfoList)
  650. {
  651. var isPk = item.DbColumnName.EqualCase(pkInfo.DbColumnName);
  652. if (isPk)
  653. {
  654. result.Add((Type)item.Value);
  655. }
  656. }
  657. }
  658. return result;
  659. }
  660. private List<Type> ReturnDefaultIdentity<Type>(EntityColumnInfo pkInfo)
  661. {
  662. List<Type> result = new List<Type>();
  663. foreach (var item in this.InsertObjs)
  664. {
  665. var insertable = this.Context.Insertable(item)
  666. .InsertColumns(this.InsertBuilder.DbColumnInfoList.Select(it => it.DbColumnName).Distinct().ToArray());
  667. if (pkInfo.UnderType == UtilConstants.IntType)
  668. {
  669. result.Add((Type)(object)insertable.ExecuteReturnIdentity());
  670. }
  671. else
  672. {
  673. result.Add((Type)(object)insertable.ExecuteReturnBigIdentity());
  674. }
  675. }
  676. return result;
  677. }
  678. #endregion
  679. }
  680. }