UnitOfWork.cs 16 KB

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