123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Bowin.Common.Linq;
- using Bowin.Common.Linq.Entity;
- using EMISOnline.Entities;
- using System.Data.SqlClient;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Validation;
- using System.Diagnostics;
- using System.Data.Entity.Core.Objects;
- using System.Data.Entity.Core.Metadata.Edm;
- using System.Data.Entity.Infrastructure;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Collections;
- using Bowin.Common.Linq.DB;
- using System.Configuration;
- namespace EMISOnline.DataLogic
- {
- public class UnitOfWork : EMISOnlineContextContainer, IDisposable
- {
- public UnitOfWork()
- : base("EMISOnlineContextContainer")
- {
- }
- public TEntity Add<TEntity>(TEntity entity) where TEntity : class
- {
- return Set<TEntity>().Add(entity);
- }
- public IEnumerable<TEntity> AddRange<TEntity>(IEnumerable<TEntity> entityList) where TEntity : class
- {
- return Set<TEntity>().AddRange(entityList);
- }
- public TEntity Attach<TEntity>(TEntity entity) where TEntity : class
- {
- return Set<TEntity>().Attach(entity);
- }
- /// <summary>
- /// 事务提交
- /// </summary>
- public void Commit()
- {
- try
- {
- SaveChanges();
- }
- catch (DbEntityValidationException dbEx)
- {
- foreach (var validationErrors in dbEx.EntityValidationErrors)
- {
- foreach (var validationError in validationErrors.ValidationErrors)
- {
- Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
- }
- }
- throw dbEx;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void BulkInsert<TEntity>(IList<TEntity> data) where TEntity : class
- {
- try
- {
- var db = GetConnection();
- data.ExecuteBulkCopy(db, typeof(TEntity).Name);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void BulkInsert<TEntity, TProperty>(IList<TEntity> data, Expression<Func<TEntity, TProperty>> relationShip)
- {
- if (!typeof(TProperty).FullName.Contains("HashSet"))
- {
- return;
- }
- var tableName1 = typeof(TEntity).Name;
- var targetProperty = (PropertyInfo)((MemberExpression)relationShip.Body).Member;
- var tableName2 = targetProperty.Name;
- var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
- var associationSet = metadata.GetItemCollection(DataSpace.SSpace)
- .GetItems<EntityContainer>().Single()
- .AssociationSets.Where(x => x.AssociationSetEnds.Any(w => w.Name == tableName1)
- && (x.AssociationSetEnds.Any(w => w.Name == tableName1 + tableName2) || x.AssociationSetEnds.Any(w => w.Name == tableName2 + tableName1))).FirstOrDefault();
- if (associationSet == null) { return; }
- bool isSourceSet;
- var targetSetProperty = typeof(AssociationSet).GetProperty("TargetSet", BindingFlags.Instance | BindingFlags.NonPublic);
- var sourceSetProperty = typeof(AssociationSet).GetProperty("SourceSet", BindingFlags.Instance | BindingFlags.NonPublic);
- var targetSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(targetSetProperty.GetValue(associationSet, null)));
- var sourceSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(sourceSetProperty.GetValue(associationSet, null)));
- var tableName = targetSet.Table;
- if (tableName == null)
- {
- tableName = sourceSet.Table;
- isSourceSet = false;
- if (tableName == null || tableName == tableName1)
- {
- return;
- }
- }
- else
- {
- isSourceSet = true;
- }
- var targetElementType = (typeof(TProperty)).GetGenericArguments()[0];
- var key1 = TableKeyDictionary.GetKeyName<TEntity>();
- var key2 = TableKeyDictionary.GetKeyName(targetElementType.Assembly.CreateInstance(targetElementType.FullName));
- var keyProperty = typeof(TEntity).GetProperty(key1);
- var targetKeyPropery = targetElementType.GetProperty(key2);
- var resultTable = new DataTable(tableName);
- var db = GetConnection();
- var columnList = db.GetTableColumns(tableName);
- if (columnList.First().ToLower() == key1.ToLower())
- {
- resultTable.Columns.Add(key1, typeof(Guid));
- resultTable.Columns.Add(key2, typeof(Guid));
- }
- else
- {
- resultTable.Columns.Add(key2, typeof(Guid));
- resultTable.Columns.Add(key1, typeof(Guid));
- }
- foreach (var dataItem in data)
- {
- IEnumerable targetHashset = (IEnumerable)targetProperty.GetValue(dataItem, null);
- foreach (var target in targetHashset)
- {
- var row = resultTable.NewRow();
- if (columnList.First().ToLower() == key1.ToLower())
- {
- row[0] = (Guid)keyProperty.GetValue(dataItem, null);
- row[1] = (Guid)targetKeyPropery.GetValue(target, null);
- }
- else
- {
- row[0] = (Guid)targetKeyPropery.GetValue(target, null);
- row[1] = (Guid)keyProperty.GetValue(dataItem, null);
- }
- resultTable.Rows.Add(row);
- }
- }
- try
- {
- BulkCopyExtensions.ExecuteBulkCopy(db, resultTable);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private SqlConnection GetConnection()
- {
- var connectionKey = typeof(EMISOnlineContextContainer).Name;
- if (SqlConnectionManager.IsGlobalConnectionStarted)
- {
- return SqlConnectionManager.GetConnection(connectionKey);
- }
- else
- {
- return new SqlConnection(ConfigurationManager.ConnectionStrings[connectionKey].ConnectionString);
- }
- }
- public TEntity Remove<TEntity>(TEntity entity) where TEntity : class
- {
- Set<TEntity>().Attach(entity);
- return Set<TEntity>().Remove(entity);
- }
- public void Remove<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : class
- {
- var entities = this.Set<TEntity>().Where(where).ToList();
- Set<TEntity>().RemoveRange(entities);
- }
- void IDisposable.Dispose()
- {
- Dispose();
- }
- public void Update<TEntity>(TEntity entity) where TEntity : class
- {
- Entry<TEntity>(entity).State = System.Data.Entity.EntityState.Modified;
- }
- public event Action<object> PostUpdate;
- public void Update<TEntity>(Expression<Func<TEntity, TEntity>> setExpression, Expression<Func<TEntity, bool>> whereExpression) where TEntity : class
- {
- var entities = this.Set<TEntity>().Where(whereExpression).ToList();
- entities.ForEach(x =>
- {
- //var updateObj = setExpression.Compile().Invoke(x);
- //this.Attach(x);
- foreach (var binding in ((MemberInitExpression)setExpression.Body).Bindings)
- {
- PropertyInfo property = (PropertyInfo)binding.Member;
- var expression = ((MemberAssignment)binding).Expression;
- if (expression is ConstantExpression)
- {
- property.SetValue(x, ((ConstantExpression)expression).Value, null);
- }
- else
- {
- property.SetValue(x, Expression.Lambda(expression, setExpression.Parameters.ToArray()).Compile()
- .DynamicInvoke(x), null);
- }
- }
- if (PostUpdate != null)
- {
- var @event = PostUpdate;
- @event(x);
- }
- });
- this.Commit();
- }
- public void Delete<TEntity>(Expression<Func<TEntity, bool>> whereExpression) where TEntity : class
- {
- var entities = this.Set<TEntity>().Where(whereExpression).ToList();
- try
- {
- ((DbContext)this).Delete(whereExpression);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void Delete<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> relationShip)
- {
- if (!typeof(TProperty).FullName.Contains("HashSet"))
- {
- return;
- }
- var tableName1 = typeof(TEntity).Name;
- var targetProperty = (PropertyInfo)((MemberExpression)relationShip.Body).Member;
- var tableName2 = targetProperty.Name;
- var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
- var associationSet = metadata.GetItemCollection(DataSpace.SSpace)
- .GetItems<EntityContainer>().Single()
- .AssociationSets.Where(x => x.AssociationSetEnds.Any(w => w.Name == tableName1)
- && (x.AssociationSetEnds.Any(w => w.Name == tableName1 + tableName2) || x.AssociationSetEnds.Any(w => w.Name == tableName2 + tableName1))).FirstOrDefault();
- if (associationSet == null) { return; }
- bool isSourceSet;
- var targetSetProperty = typeof(AssociationSet).GetProperty("TargetSet", BindingFlags.Instance | BindingFlags.NonPublic);
- var sourceSetProperty = typeof(AssociationSet).GetProperty("SourceSet", BindingFlags.Instance | BindingFlags.NonPublic);
- var targetSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(targetSetProperty.GetValue(associationSet, null)));
- var sourceSet = ((System.Data.Entity.Core.Metadata.Edm.EntitySet)(sourceSetProperty.GetValue(associationSet, null)));
- var tableName = targetSet.Table;
- if (tableName == null)
- {
- tableName = sourceSet.Table;
- isSourceSet = false;
- if (tableName == null || tableName == tableName1)
- {
- return;
- }
- }
- else
- {
- isSourceSet = true;
- }
- var targetElementType = (typeof(TProperty)).GetGenericArguments()[0];
- var key1 = TableKeyDictionary.GetKeyName<TEntity>();
- var key2 = TableKeyDictionary.GetKeyName(targetElementType.Assembly.CreateInstance(targetElementType.FullName));
- var keyProperty = typeof(TEntity).GetProperty(key1);
- var targetKeyPropery = targetElementType.GetProperty(key2);
- var resultTable = new DataTable(tableName);
- if (isSourceSet)
- {
- resultTable.Columns.Add(key1, typeof(Guid));
- resultTable.Columns.Add(key2, typeof(Guid));
- }
- else
- {
- resultTable.Columns.Add(key2, typeof(Guid));
- resultTable.Columns.Add(key1, typeof(Guid));
- }
- IEnumerable targetHashset = (IEnumerable)targetProperty.GetValue(entity, null);
- foreach (var target in targetHashset)
- {
- var row = resultTable.NewRow();
- if (isSourceSet)
- {
- row[0] = (Guid)keyProperty.GetValue(entity, null);
- row[1] = (Guid)targetKeyPropery.GetValue(target, null);
- }
- else
- {
- row[0] = (Guid)targetKeyPropery.GetValue(target, null);
- row[1] = (Guid)keyProperty.GetValue(entity, null);
- }
- resultTable.Rows.Add(row);
- }
- try
- {
- var db = GetConnection();
- db.Delete(tableName, key1, (Guid)keyProperty.GetValue(entity, null));
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- int ExecuteSQL(string sql, params object[] parameters)
- {
- return this.Database.ExecuteSqlCommand(sql, parameters);
- }
- public void BatchUpdate<TKey>(string tableName, string columnName, object value, IList<TKey> idList)
- {
- var assembly = typeof(EMISOnlineContextContainer).Assembly;
- var entityType = assembly.GetTypes().Where(x => x.Name.ToLower() == tableName.ToLower()).FirstOrDefault();
- var methodInfo = typeof(UnitOfWork).GetMethods()
- .Where(x => x.ContainsGenericParameters && x.GetGenericArguments().Length == 2 && x.Name == "BatchUpdate").FirstOrDefault();
- methodInfo = methodInfo
- .MakeGenericMethod(entityType, typeof(TKey));
- methodInfo.Invoke(this, new object[] { columnName, value, idList });
- }
- public void BatchUpdate<TEntity, TKey>(string columnName, object value, IList<TKey> idList) where TEntity : class
- {
- ExpressionFactory<TEntity> factory = new ExpressionFactory<TEntity>(Set<TEntity>());
- var para = Expression.Parameter(typeof(TEntity));
- var property = typeof(TEntity).GetProperty(columnName);
- var newExpression = Expression.New(typeof(TEntity).GetConstructor(new Type[] { }));
- var bindExpression = Expression.Bind(property, GetValueExpression(value, property));
- var memberExpression = Expression.MemberInit(newExpression, new MemberBinding[] { bindExpression });
- Expression<Func<TEntity, TEntity>> setExpression = Expression.Lambda<Func<TEntity, TEntity>>(memberExpression, para);
- Expression<Func<TEntity, bool>> whereExpression = factory.DynamicInExpression(TableKeyDictionary.GetKeyName<TEntity>(), idList);
- this.Update(setExpression, whereExpression);
- }
- private Expression GetValueExpression(object value, PropertyInfo property)
- {
- if (property.PropertyType == typeof(Guid) || property.PropertyType == typeof(Guid?))
- {
- return Expression.Constant(Guid.Parse(value.ToString()));
- }
- else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
- {
- return Expression.Constant(int.Parse(value.ToString()));
- }
- else if (property.PropertyType == typeof(short) || property.PropertyType == typeof(short?))
- {
- return Expression.Constant(short.Parse(value.ToString()));
- }
- else if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
- {
- return Expression.Constant(bool.Parse(value.ToString()));
- }
- else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal?))
- {
- return Expression.Constant(decimal.Parse(value.ToString()));
- }
- else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
- {
- return Expression.Constant(DateTime.Parse(value.ToString()));
- }
- else
- {
- return Expression.Convert(Expression.Constant(value), property.PropertyType);
- }
- }
- }
- }
|