HRUnitOfWork.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using EMIS.Entities.HRServices;
  6. using EMIS.Utility.Log;
  7. using System.Data.Entity.Validation;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using System.Data.Entity.Infrastructure;
  11. using System.Data.Entity.Core.Metadata.Edm;
  12. using System.Data;
  13. using System.Collections;
  14. using Bowin.Common.Linq;
  15. using System.Data.SqlClient;
  16. using Bowin.Common.Linq.DB;
  17. using System.Configuration;
  18. using System.Data.Entity;
  19. using Bowin.Common.Linq.Entity;
  20. using System.Diagnostics;
  21. namespace EMIS.DataLogic
  22. {
  23. public class HRUnitOfWork : HRServiceContextContainer, IDisposable
  24. {
  25. public HRUnitOfWork()
  26. : base("HRServiceContextContainer")
  27. {
  28. }
  29. public TEntity Add<TEntity>(TEntity entity) where TEntity : class
  30. {
  31. return Set<TEntity>().Add(entity);
  32. }
  33. public IEnumerable<TEntity> AddRange<TEntity>(IEnumerable<TEntity> entityList) where TEntity : class
  34. {
  35. return Set<TEntity>().AddRange(entityList);
  36. }
  37. public TEntity Attach<TEntity>(TEntity entity) where TEntity : class
  38. {
  39. return Set<TEntity>().Attach(entity);
  40. }
  41. /// <summary>
  42. /// 事务提交
  43. /// </summary>
  44. public void Commit()
  45. {
  46. var logs = DbLog.GetLog(this.ChangeTracker).Concat(
  47. DbLog.GetRelationshipLog(this)).ToList();
  48. try
  49. {
  50. SaveChanges();
  51. logs.ForEach(x => x.IsSuccess = true);
  52. LogUnitOfWork.WriteLogs(logs);
  53. }
  54. catch (DbEntityValidationException dbEx)
  55. {
  56. logs.ForEach(x => x.IsSuccess = false);
  57. LogUnitOfWork.WriteLogs(logs);
  58. foreach (var validationErrors in dbEx.EntityValidationErrors)
  59. {
  60. foreach (var validationError in validationErrors.ValidationErrors)
  61. {
  62. Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
  63. }
  64. }
  65. throw dbEx;
  66. }
  67. catch (Exception ex)
  68. {
  69. logs.ForEach(x => x.IsSuccess = false);
  70. LogUnitOfWork.WriteLogs(logs);
  71. throw ex;
  72. }
  73. }
  74. public void BulkInsert<TEntity>(IList<TEntity> data) where TEntity : class
  75. {
  76. var logList = DbLog.GetBulkInsertLog(data);
  77. try
  78. {
  79. var db = GetConnection();
  80. data.ExecuteBulkCopy(db, typeof(TEntity).Name);
  81. logList.ForEach(x => x.IsSuccess = true);
  82. LogUnitOfWork.WriteLogs(logList);
  83. }
  84. catch (Exception ex)
  85. {
  86. logList.ForEach(x => x.IsSuccess = false);
  87. LogUnitOfWork.WriteLogs(logList);
  88. throw ex;
  89. }
  90. }
  91. public void BulkInsert<TEntity, TProperty>(IList<TEntity> data, Expression<Func<TEntity, TProperty>> relationShip)
  92. {
  93. if (!typeof(TProperty).FullName.Contains("HashSet"))
  94. {
  95. return;
  96. }
  97. var tableName1 = typeof(TEntity).Name;
  98. var targetProperty = (PropertyInfo)((MemberExpression)relationShip.Body).Member;
  99. var tableName2 = targetProperty.Name;
  100. var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
  101. var associationSet = metadata.GetItemCollection(DataSpace.SSpace)
  102. .GetItems<EntityContainer>().Single()
  103. .AssociationSets.Where(x => x.AssociationSetEnds.Any(w => w.Name == tableName1)
  104. && (x.AssociationSetEnds.Any(w => w.Name == tableName1 + tableName2) || x.AssociationSetEnds.Any(w => w.Name == tableName2 + tableName1))).FirstOrDefault();
  105. if (associationSet == null) { return; }
  106. bool isSourceSet;
  107. var targetSetProperty = typeof(AssociationSet).GetProperty("TargetSet", BindingFlags.Instance | BindingFlags.NonPublic);
  108. var sourceSetProperty = typeof(AssociationSet).GetProperty("SourceSet", BindingFlags.Instance | BindingFlags.NonPublic);
  109. var targetSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(targetSetProperty.GetValue(associationSet, null)));
  110. var sourceSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(sourceSetProperty.GetValue(associationSet, null)));
  111. var tableName = targetSet.Table;
  112. if (tableName == null)
  113. {
  114. tableName = sourceSet.Table;
  115. isSourceSet = false;
  116. if (tableName == null || tableName == tableName1)
  117. {
  118. return;
  119. }
  120. }
  121. else
  122. {
  123. isSourceSet = true;
  124. }
  125. var targetElementType = (typeof(TProperty)).GetGenericArguments()[0];
  126. var key1 = TableKeyDictionary.GetKeyName<TEntity>();
  127. var key2 = TableKeyDictionary.GetKeyName(targetElementType.Assembly.CreateInstance(targetElementType.FullName));
  128. var keyProperty = typeof(TEntity).GetProperty(key1);
  129. var targetKeyPropery = targetElementType.GetProperty(key2);
  130. var resultTable = new DataTable(tableName);
  131. var db = GetConnection();
  132. var columnList = db.GetTableColumns(tableName);
  133. if (columnList.First().ToLower() == key1.ToLower())
  134. {
  135. resultTable.Columns.Add(key1, typeof(Guid));
  136. resultTable.Columns.Add(key2, typeof(Guid));
  137. }
  138. else
  139. {
  140. resultTable.Columns.Add(key2, typeof(Guid));
  141. resultTable.Columns.Add(key1, typeof(Guid));
  142. }
  143. foreach (var dataItem in data)
  144. {
  145. IEnumerable targetHashset = (IEnumerable)targetProperty.GetValue(dataItem, null);
  146. foreach (var target in targetHashset)
  147. {
  148. var row = resultTable.NewRow();
  149. if (columnList.First().ToLower() == key1.ToLower())
  150. {
  151. row[0] = (Guid)keyProperty.GetValue(dataItem, null);
  152. row[1] = (Guid)targetKeyPropery.GetValue(target, null);
  153. }
  154. else
  155. {
  156. row[0] = (Guid)targetKeyPropery.GetValue(target, null);
  157. row[1] = (Guid)keyProperty.GetValue(dataItem, null);
  158. }
  159. resultTable.Rows.Add(row);
  160. }
  161. }
  162. var logList = DbLog.GetBulkInsertLog(resultTable, tableName);
  163. try
  164. {
  165. BulkCopyExtensions.ExecuteBulkCopy(db, resultTable);
  166. logList.ForEach(x => x.IsSuccess = true);
  167. LogUnitOfWork.WriteLogs(logList);
  168. }
  169. catch (Exception ex)
  170. {
  171. logList.ForEach(x => x.IsSuccess = false);
  172. LogUnitOfWork.WriteLogs(logList);
  173. throw ex;
  174. }
  175. }
  176. private SqlConnection GetConnection()
  177. {
  178. var connectionKey = typeof(HRServiceContextContainer).Name;
  179. if (SqlConnectionManager.IsGlobalConnectionStarted)
  180. {
  181. return SqlConnectionManager.GetConnection(connectionKey);
  182. }
  183. else
  184. {
  185. return new SqlConnection(ConfigurationManager.ConnectionStrings[connectionKey].ConnectionString);
  186. }
  187. }
  188. public TEntity Remove<TEntity>(TEntity entity) where TEntity : class
  189. {
  190. Set<TEntity>().Attach(entity);
  191. return Set<TEntity>().Remove(entity);
  192. }
  193. public void Remove<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : class
  194. {
  195. var entities = this.Set<TEntity>().Where(where).ToList();
  196. Set<TEntity>().RemoveRange(entities);
  197. }
  198. public void RemoveRange<TEntity>(HashSet<TEntity> entities) where TEntity : class
  199. {
  200. Set<TEntity>().RemoveRange(entities);
  201. }
  202. void IDisposable.Dispose()
  203. {
  204. Dispose();
  205. }
  206. public void Update<TEntity>(TEntity entity) where TEntity : class
  207. {
  208. Entry<TEntity>(entity).State = System.Data.Entity.EntityState.Modified;
  209. }
  210. public event Action<object> PostUpdate;
  211. public void Update<TEntity>(Expression<Func<TEntity, TEntity>> setExpression, Expression<Func<TEntity, bool>> whereExpression) where TEntity : class
  212. {
  213. var entities = this.Set<TEntity>().Where(whereExpression).ToList();
  214. entities.ForEach(x =>
  215. {
  216. //var updateObj = setExpression.Compile().Invoke(x);
  217. //this.Attach(x);
  218. foreach (var binding in ((MemberInitExpression)setExpression.Body).Bindings)
  219. {
  220. PropertyInfo property = (PropertyInfo)binding.Member;
  221. var expression = ((MemberAssignment)binding).Expression;
  222. if (expression is ConstantExpression)
  223. {
  224. property.SetValue(x, ((ConstantExpression)expression).Value, null);
  225. }
  226. else
  227. {
  228. property.SetValue(x, Expression.Lambda(expression, setExpression.Parameters.ToArray()).Compile()
  229. .DynamicInvoke(x), null);
  230. }
  231. }
  232. if (PostUpdate != null)
  233. {
  234. var @event = PostUpdate;
  235. @event(x);
  236. }
  237. });
  238. this.Commit();
  239. }
  240. public void Delete<TEntity>(Expression<Func<TEntity, bool>> whereExpression) where TEntity : class
  241. {
  242. var entities = this.Set<TEntity>().Where(whereExpression).ToList();
  243. var logList = DbLog.GetDeleteLog(entities);
  244. try
  245. {
  246. ((DbContext)this).Delete(whereExpression);
  247. logList.ForEach(x => x.IsSuccess = true);
  248. LogUnitOfWork.WriteLogs(logList);
  249. }
  250. catch (Exception ex)
  251. {
  252. logList.ForEach(x => x.IsSuccess = false);
  253. LogUnitOfWork.WriteLogs(logList);
  254. throw ex;
  255. }
  256. //entities.ForEach(x => this.Remove(x));
  257. //this.Commit();
  258. }
  259. public void Delete<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> relationShip)
  260. {
  261. if (!typeof(TProperty).FullName.Contains("HashSet"))
  262. {
  263. return;
  264. }
  265. var tableName1 = typeof(TEntity).Name;
  266. var targetProperty = (PropertyInfo)((MemberExpression)relationShip.Body).Member;
  267. var tableName2 = targetProperty.Name;
  268. var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
  269. var associationSet = metadata.GetItemCollection(DataSpace.SSpace)
  270. .GetItems<EntityContainer>().Single()
  271. .AssociationSets.Where(x => x.AssociationSetEnds.Any(w => w.Name == tableName1)
  272. && (x.AssociationSetEnds.Any(w => w.Name == tableName1 + tableName2) || x.AssociationSetEnds.Any(w => w.Name == tableName2 + tableName1))).FirstOrDefault();
  273. if (associationSet == null) { return; }
  274. bool isSourceSet;
  275. var targetSetProperty = typeof(AssociationSet).GetProperty("TargetSet", BindingFlags.Instance | BindingFlags.NonPublic);
  276. var sourceSetProperty = typeof(AssociationSet).GetProperty("SourceSet", BindingFlags.Instance | BindingFlags.NonPublic);
  277. var targetSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(targetSetProperty.GetValue(associationSet, null)));
  278. var sourceSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(sourceSetProperty.GetValue(associationSet, null)));
  279. var tableName = targetSet.Table;
  280. if (tableName == null)
  281. {
  282. tableName = sourceSet.Table;
  283. isSourceSet = false;
  284. if (tableName == null || tableName == tableName1)
  285. {
  286. return;
  287. }
  288. }
  289. else
  290. {
  291. isSourceSet = true;
  292. }
  293. var targetElementType = (typeof(TProperty)).GetGenericArguments()[0];
  294. var key1 = TableKeyDictionary.GetKeyName<TEntity>();
  295. var key2 = TableKeyDictionary.GetKeyName(targetElementType.Assembly.CreateInstance(targetElementType.FullName));
  296. var keyProperty = typeof(TEntity).GetProperty(key1);
  297. var targetKeyPropery = targetElementType.GetProperty(key2);
  298. var resultTable = new DataTable(tableName);
  299. if (isSourceSet)
  300. {
  301. resultTable.Columns.Add(key1, typeof(Guid));
  302. resultTable.Columns.Add(key2, typeof(Guid));
  303. }
  304. else
  305. {
  306. resultTable.Columns.Add(key2, typeof(Guid));
  307. resultTable.Columns.Add(key1, typeof(Guid));
  308. }
  309. IEnumerable targetHashset = (IEnumerable)targetProperty.GetValue(entity, null);
  310. foreach (var target in targetHashset)
  311. {
  312. var row = resultTable.NewRow();
  313. if (isSourceSet)
  314. {
  315. row[0] = (Guid)keyProperty.GetValue(entity, null);
  316. row[1] = (Guid)targetKeyPropery.GetValue(target, null);
  317. }
  318. else
  319. {
  320. row[0] = (Guid)targetKeyPropery.GetValue(target, null);
  321. row[1] = (Guid)keyProperty.GetValue(entity, null);
  322. }
  323. resultTable.Rows.Add(row);
  324. }
  325. var logList = DbLog.GetDeleteLog(resultTable, tableName);
  326. try
  327. {
  328. var db = GetConnection();
  329. db.Delete(tableName, key1, (Guid)keyProperty.GetValue(entity, null));
  330. logList.ForEach(x => x.IsSuccess = true);
  331. LogUnitOfWork.WriteLogs(logList);
  332. }
  333. catch (Exception ex)
  334. {
  335. logList.ForEach(x => x.IsSuccess = false);
  336. LogUnitOfWork.WriteLogs(logList);
  337. throw ex;
  338. }
  339. }
  340. int ExecuteSQL(string sql, params object[] parameters)
  341. {
  342. return this.Database.ExecuteSqlCommand(sql, parameters);
  343. }
  344. public void BatchUpdate<TKey>(string tableName, string columnName, object value, IList<TKey> idList)
  345. {
  346. var assembly = typeof(HRServiceContextContainer).Assembly;
  347. var entityType = assembly.GetTypes().Where(x => x.Name.ToLower() == tableName.ToLower()).FirstOrDefault();
  348. var methodInfo = typeof(UnitOfWork).GetMethods()
  349. .Where(x => x.ContainsGenericParameters && x.GetGenericArguments().Length == 2 && x.Name == "BatchUpdate").FirstOrDefault();
  350. methodInfo = methodInfo
  351. .MakeGenericMethod(entityType, typeof(TKey));
  352. methodInfo.Invoke(this, new object[] { columnName, value, idList });
  353. }
  354. public void BatchUpdate<TEntity, TKey>(string columnName, object value, IList<TKey> idList) where TEntity : class
  355. {
  356. ExpressionFactory<TEntity> factory = new ExpressionFactory<TEntity>(Set<TEntity>());
  357. var para = Expression.Parameter(typeof(TEntity));
  358. var property = typeof(TEntity).GetProperty(columnName);
  359. var newExpression = Expression.New(typeof(TEntity).GetConstructor(new Type[] { }));
  360. var bindExpression = Expression.Bind(property, GetValueExpression(value, property));
  361. var memberExpression = Expression.MemberInit(newExpression, new MemberBinding[] { bindExpression });
  362. Expression<Func<TEntity, TEntity>> setExpression = Expression.Lambda<Func<TEntity, TEntity>>(memberExpression, para);
  363. Expression<Func<TEntity, bool>> whereExpression = factory.DynamicInExpression(TableKeyDictionary.GetKeyName<TEntity>(), idList);
  364. this.Update(setExpression, whereExpression);
  365. }
  366. private Expression GetValueExpression(object value, PropertyInfo property)
  367. {
  368. if (property.PropertyType == typeof(Guid) || property.PropertyType == typeof(Guid?))
  369. {
  370. return Expression.Constant(Guid.Parse(value.ToString()));
  371. }
  372. else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
  373. {
  374. return Expression.Constant(int.Parse(value.ToString()));
  375. }
  376. else if (property.PropertyType == typeof(short) || property.PropertyType == typeof(short?))
  377. {
  378. return Expression.Constant(short.Parse(value.ToString()));
  379. }
  380. else if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
  381. {
  382. return Expression.Constant(bool.Parse(value.ToString()));
  383. }
  384. else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal?))
  385. {
  386. return Expression.Constant(decimal.Parse(value.ToString()));
  387. }
  388. else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
  389. {
  390. return Expression.Constant(DateTime.Parse(value.ToString()));
  391. }
  392. else
  393. {
  394. return Expression.Convert(Expression.Constant(value), property.PropertyType);
  395. }
  396. }
  397. }
  398. }