private static void updateSingle(IEntity obj, EntityInfo entityInfo) { if (DbContext.shouldTransaction()) { var conn = DbContext.getConnection(entityInfo); IDbCommand cmd = DataFactory.GetCommand(getUpdateSql(entityInfo), conn); if (cmd.Connection.State == Data.ConnectionState.Closed) { cmd.Connection.Open(); OrmHelper.initCount++; LogManager.GetLogger("Class:System.ORM.Operation.UpdateOperation Method:updateSingle").Info("数据库连接已开启【" + OrmHelper.initCount + "】"); } OrmHelper.SetParameters(cmd, "update", obj, entityInfo); DataFactory.SetParameter(cmd, "Id", obj.Id); cmd.ExecuteNonQuery(); } else { using (var conn = DbContext.getConnection(entityInfo)) { IDbCommand cmd = DataFactory.GetCommand(getUpdateSql(entityInfo), DbContext.getConnection(entityInfo)); if (cmd.Connection.State == Data.ConnectionState.Closed) { cmd.Connection.Open(); OrmHelper.initCount++; LogManager.GetLogger("Class:System.ORM.Operation.UpdateOperation Method:updateSingle").Info("数据库连接已开启【" + OrmHelper.initCount + "】"); } OrmHelper.SetParameters(cmd, "update", obj, entityInfo); DataFactory.SetParameter(cmd, "Id", obj.Id); cmd.ExecuteNonQuery(); } } }
private IQueryable <TEF> AddSearchParameters(IQueryable <TEF> q, DTO.StdInputs sci) { if (sci.SearchParameters != null && sci.SearchParameters.Count > 0) { int count = sci.SearchParameters.Count; dynamic expAll = null; bool orJoiner = false; for (int i = 0; i < count; i++) { var sp = sci.SearchParameters.ElementAt(i); var exp = OrmHelper.GetBinaryExpression <TEF>(sp.Column, (int)sp.Compare, sp.Value); if (i == 0) { expAll = exp; } else { expAll = orJoiner ? OrmHelper.ExpressionOr(expAll, exp) : OrmHelper.ExpressionAnd(expAll, exp); } orJoiner = sp.Or; } return(OrmHelper.WhereWrapper <TEF>(q, expAll)); } return(q); }
public static String GetSameTypeIds(Type throughType, Type t, int id) { // 1029 ObjectInfo state = new ObjectInfo(throughType); String relationPropertyName = state.EntityInfo.GetRelationPropertyName(t); EntityPropertyInfo info = state.EntityInfo.FindRelationProperty(t); String ids = ObjectDB.Find(state, relationPropertyName + ".Id=" + id).get(info.Name + ".Id"); EntityPropertyInfo property = state.EntityInfo.GetProperty(relationPropertyName); String sql = String.Format("select distinct {0} from {1} where {2} in ({3}) and {0}<>{4}", property.ColumnName, state.EntityInfo.TableName, info.ColumnName, ids, id); IDbCommand command = DataFactory.GetCommand(sql, DbContext.getConnection(state.EntityInfo)); IDataReader rd = null; StringBuilder builder = new StringBuilder(); try { rd = command.ExecuteReader(); while (rd.Read()) { builder.Append(rd[0]); builder.Append(","); } } catch (Exception exception) { logger.Error(exception.Message); throw new OrmException(exception.Message, exception); } finally { OrmHelper.CloseDataReader(rd); } return(builder.ToString().TrimEnd(',')); }
private static void updateSingle(IEntity obj, EntityInfo entityInfo) { IDbCommand cmd = DataFactory.GetCommand(getUpdateSql(entityInfo), DbContext.getConnection(entityInfo)); OrmHelper.SetParameters(cmd, "update", obj, entityInfo); DataFactory.SetParameter(cmd, "Id", obj.Id); cmd.ExecuteNonQuery(); }
internal static IList Find(ConditionInfo condition) { IList results = ObjectPool.FindByQuery(condition); if (results != null) { return(results); } if ("*".Equals(condition.SelectedItem)) { condition.State.includeAll(); } else { condition.State.include(SqlBuilder.GetIncludeProperty(condition.SelectedItem)); } IList includeEntityPropertyList = condition.State.Includer.EntityPropertyList; IDbCommand cmd = DataFactory.GetCommand(condition.Sql, DbContext.getConnection(condition.State.EntityInfo)); foreach (String key in condition.Parameters.Keys) { DataFactory.SetParameter(cmd, key, condition.Parameters[key]); } Hashtable hashtable = new Hashtable(); IDataReader record = null; results = new ArrayList(); try { record = cmd.ExecuteReader(); while (record.Read()) { EntityPropertyUtil.Fill_EntityProperty_Ids(record, includeEntityPropertyList, ref hashtable); results.Add(FillUtil.Populate(record, condition.State)); } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); throw new OrmException(ex.Message, ex); } finally { OrmHelper.CloseDataReader(record); } if (results.Count == 0) { return(results); } return(EntityPropertyUtil.setEntityProperty(condition.State, results, hashtable)); }
private Boolean isAddIdentityKey(Type t) { if (OrmHelper.IsEntityBase(t.BaseType)) { return(true); } if (t.BaseType.IsAbstract) { return(true); } return(false); }
public async Task <DTO.ReturnResponse <DTO.MasterMap> > Add(DTO.MasterMap inMap, long personId) { var response = new DTO.ReturnResponse <DTO.MasterMap>(); if (inMap.Columns.Count == 0) { response.Errors.Add("Zero Columns? Really?"); } var mmap = _mapper.Map <MasterMap>(inMap); OrmHelper.SetAuditColumns(ref mmap, true, personId); var Headers = new List <string>(); var SqlNames = new List <string>(); foreach (var col in mmap.Columns) { if (Headers.Contains(col.Header)) { response.Errors.Add($"Header not unique {col.Header}"); } if (SqlNames.Contains(col.ColumnName)) { response.Errors.Add($"Header not unique {col.Header}"); } if (response.Success) { var tcol = col; OrmHelper.SetAuditColumns(ref tcol, true, personId); } } if (response.Success) { try { _db.MasterMap.Add(mmap); await _db.SaveChangesAsync(); response.Result = _mapper.Map <DTO.MasterMap>(mmap); } catch (Exception ex) { response.Errors.Add(ex.Message); } } return(response); }
private static Result Insert(IEntity obj, EntityInfo entityInfo, Boolean isInsertParent) { Result result = Validator.Validate(obj, "insert"); if (result.HasErrors) { return(result); } if (isInsertParent && entityInfo.Parent != null) { IEntity objP = Entity.New(entityInfo.Type.BaseType.FullName); List <EntityPropertyInfo> eplist = Entity.GetInfo(objP).SavedPropertyList; foreach (EntityPropertyInfo info in eplist) { if (info.IsList) { continue; } objP.set(info.Name, obj.get(info.Name)); } ObjectDB.Insert(objP); obj.Id = objP.Id; } List <IInterceptor> ilist = MappingClass.Instance.InterceptorList; for (int i = 0; i < ilist.Count; i++) { ilist[i].BeforInsert(obj); } IDbCommand cmd = DataFactory.GetCommand(getInsertSql(entityInfo), DbContext.getConnection(entityInfo)); OrmHelper.SetParameters(cmd, "insert", obj, entityInfo); lock (objLock) { executeCmd(cmd, entityInfo, ref obj); } for (int i = 0; i < ilist.Count; i++) { ilist[i].AfterInsert(obj); } CacheUtil.CheckCountCache("insert", obj, entityInfo); result.Info = obj; CacheTime.updateTable(obj.GetType()); return(result); }
public async Task <DTO.ReturnResponse <DTO.Person> > Add(DTO.Person Person) { var ret = new DTO.ReturnResponse <DTO.Person>(); var val = _mapper.Map <Person>(Person); OrmHelper.SetAuditColumns <Person>(ref val, true, 1); _db.Person.Add(val); await _db.SaveChangesAsync(); ret.Result = _mapper.Map <DTO.Person>(val); return(ret); }
public async Task <DTO.ReturnResponse <DTO.PersonMap> > AddMap(DTO.PersonMapAdd map, long personId) { var response = new DTO.ReturnResponse <DTO.PersonMap>(); if (map.Columns.Count == 0) { response.Errors.Add("Zero Columns? Really?"); } var mmap = _db.MasterMap.Include(o => o.Columns).First(o => o.Id == map.MasterMapId); if (mmap == null) { response.Errors.Add($"Invalid MasterMapID {map.MasterMapId}"); } var pmap = _mapper.Map <PersonMap>(map); OrmHelper.SetAuditColumns(ref pmap, true, personId); foreach (var col in pmap.Columns) { if (mmap.Columns.First(o => o.Header == col.OurHeader) == null) { response.Errors.Add($"header does not exist {col.OurHeader}"); } if (response.Success) { var tcol = col; OrmHelper.SetAuditColumns(ref tcol, true, personId); } } if (response.Success) { try { _db.PersonMap.Add(pmap); await _db.SaveChangesAsync(); response.Result = _mapper.Map <DTO.PersonMap>(pmap); } catch (Exception ex) { response.Errors.Add(ex.Message); } } return(response); }
public async Task Run(IMapper mapper, IQueryable <TEF> q, DTO.StdCollectionInputs sci) { var tq = q; if (!sci.IncludeDeleted) { tq = OrmHelper.EqualToProperty <TEF>(tq, "Deleted", false); } tq = AddSearchParameters(tq, sci); TotalCount = tq.Count(); string sIncludeDeleted = sci.IncludeDeleted ? "true" : "false"; string QM = sci.Route.IndexOf("?") == -1 ? "?" : "&"; q = AddSearchParameters(q, sci); q = OrmHelper.AddStdCollectionParameters <TEF>(q, sci.Offset, sci.Limit, sci.IncludeDeleted, sci.Sort); Items = mapper.Map <TDTO[]>(await q.ToArrayAsync()); ItemCount = Items.Count(); Paging.Self = $"{sci.Offset}"; Paging.First = $"0"; if (sci.Limit < TotalCount && sci.Limit > 0) { if (sci.Offset > 0) { Paging.Prev = $"{(sci.Offset > 0 ? sci.Offset - sci.Limit : 0)}"; } if (sci.Offset < TotalCount) { Paging.Next = $"{(sci.Offset + sci.Limit)}"; Paging.Last = $"{(TotalCount - sci.Limit)}"; } if (sci.Offset + sci.Limit >= TotalCount) { Paging.Next = null; } } }
public async Task <DTO.ReturnResponse <DTO.Company> > Add(DTO.CompanyAdd inVal) { var ret = new DTO.ReturnResponse <DTO.Company>(); var dbVal = _mapper.Map <Company>(inVal); OrmHelper.SetAuditColumns <Company>(ref dbVal, true, 1); _db.Company.Add(dbVal); await _db.SaveChangesAsync(); ret.Result = _mapper.Map <DTO.Company>(dbVal); return(ret); }
public static OrmHelper GetOrmHelper() { OrmHelper result = null; switch (OrmFactory.DbType) { case "mysql": result = new MySqlOrmHelper(); break; case "oracle": result = new OracleOrmHelper(); break; } return(result); }
private static IEntity findById_Private(int id, ObjectInfo state) { if (id < 0) { return(null); } IEntity result = null; SqlBuilder sh = new SqlBuilder(state.EntityInfo); processIncluder(state.Includer); String sql = sh.GetFindById(id, state.Includer.SelectedProperty); IDbCommand cmd = DataFactory.GetCommand(sql, DbContext.getConnection(state.EntityInfo)); IList list = new ArrayList(); IDataReader rd = null; try { rd = cmd.ExecuteReader(); while (rd.Read()) { list.Add(FillUtil.Populate(rd, state)); } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); throw ex; } finally { OrmHelper.CloseDataReader(rd); } if (list.Count > 0) { result = list[0] as IEntity; } result = setEntityProperty(result, id, state); return(result); }
public static String GetSameTypeIds(Type throughType, Type t, int id) { // 1029 ObjectInfo state = new ObjectInfo(throughType); String relationPropertyName = state.EntityInfo.GetRelationPropertyName(t); EntityPropertyInfo info = state.EntityInfo.FindRelationProperty(t); String ids = ObjectDb.Find(state, relationPropertyName + ".Id=" + id).get(info.Name + ".Id"); EntityPropertyInfo property = state.EntityInfo.GetProperty(relationPropertyName); String sql = String.Format("select distinct {0} from {1} where {2} in ({3}) and {0}<>{4}", property.ColumnName, state.EntityInfo.TableName, info.ColumnName, ids, id); IDbCommand command = DataFactory.GetCommand(sql, DbContext.getConnection(state.EntityInfo)); IDataReader rd = null; StringBuilder builder = new StringBuilder(); try { rd = command.ExecuteReader(); while (rd.Read()) { builder.Append(rd[0]); builder.Append(","); } } catch (Exception exception) { logger.Error(exception.Message); throw exception; } finally { if (command.Connection.State != ConnectionState.Closed) { command.Connection.Close(); command.Connection.Dispose(); OrmHelper.clostCount++; LogManager.GetLogger("Class:System.ORM.Operation.FindRelationOperation Method:GetSameTypeIds").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】"); } OrmHelper.CloseDataReader(rd); } return(builder.ToString().TrimEnd(',')); }
private static IQueryable <T> ApplyOrderBy <T>(IQueryable <T> collection, OrderByInfo orderByInfo) { Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; string prop = orderByInfo.PropertyName; // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = OrmHelper.GetPropertyInfo <T>(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; Type delegateType = typeof(Func <,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); string methodName = String.Empty; if (!orderByInfo.Initial && collection is IOrderedQueryable <T> ) { methodName = orderByInfo.Direction == SortDirection.Ascending ? "ThenBy" : "ThenByDescending"; } else { methodName = orderByInfo.Direction == SortDirection.Ascending ? "OrderBy" : "OrderByDescending"; } //TODO: apply caching to the generic methodsinfos? return((IOrderedQueryable <T>) typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { collection, lambda })); }
public async Task <DTO.ImportPost> ImportSheet(DTO.ImportPost import) { ExcelPackage sheet = new ExcelPackage(import.Stream); var pMap = _db.PersonMap .Include(o => o.Columns) .Include(o => o.MasterMap) .Include(o => o.MasterMap.Columns) .FirstOrDefault(o => o.Id == import.PersonMapId); var mMap = pMap.MasterMap; var blobber = new Azure.Blobber(); var bName = await blobber.Upload(import.Stream, mMap.TableName.ToLower()); var importRec = new Import() { FileName = import.FileName, FileLength = import.FileLength, PersonMapID = import.PersonMapId, Status = 1, BlobName = bName }; OrmHelper.SetAuditColumns <Import>(ref importRec, true, import.PersonId); _db.Import.Add(importRec); await _db.SaveChangesAsync(); import.ImportId = importRec.Id; var headers = new Dictionary <string, int>(); int sheetNo = 0; foreach (ExcelWorksheet worksheet in sheet.Workbook.Worksheets) { if (worksheet == null) { continue; } if (worksheet.Dimension == null) { continue; } int cols = worksheet.Dimension.Columns; int rows = worksheet.Dimension.Rows; if (cols == 0 || rows == 0) { continue; } if (rows > 0) { for (int i = 1; i <= cols; i++) { //loop for headers string header = worksheet.GetValue(1, i).ToString().Trim(); if (!headers.ContainsKey(header)) { headers.Add(header, i); } } } var MTC = new Dictionary <string, string>(); foreach (var el in pMap.Columns) { if (headers.ContainsKey(el.TheirHeader)) { var fieldName = mMap.Columns.First(o => o.Header == el.OurHeader).ColumnName; MTC.Add(fieldName, $"{headers[el.TheirHeader]}|{el.Regex}"); } else { Debug.WriteLine(el.TheirHeader); } } import.SheetNo = sheetNo; switch (mMap.TableName.ToLower()) { case "sale": DoSales(worksheet, MTC, mMap, import); break; } sheetNo++; } importRec.Status = 2; importRec.WarnRows = import.WarnRows; importRec.SkipRows = import.SkipRows; await _db.SaveChangesAsync(); return(import); }
private static Result Insert(IEntity obj, EntityInfo entityInfo, Boolean isInsertParent) { Result result = Validator.Validate(obj, "insert"); if (result.HasErrors) { return(result); } if (isInsertParent && entityInfo.Parent != null) { IEntity objP = Entity.New(entityInfo.Type.BaseType.FullName); List <EntityPropertyInfo> eplist = Entity.GetInfo(objP).SavedPropertyList; foreach (EntityPropertyInfo info in eplist) { if (info.IsList) { continue; } objP.set(info.Name, obj.get(info.Name)); } ObjectDb.Insert(objP); obj.Id = objP.Id; } List <IInterceptor> ilist = MappingClass.Instance.InterceptorList; for (int i = 0; i < ilist.Count; i++) { ilist[i].BeforInsert(obj); } var conn = DbContext.getConnection(entityInfo); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); OrmHelper.initCount++; LogManager.GetLogger("Class:System.Data.InsertOperation Method:Insert").Info("数据库连接已开启【" + OrmHelper.initCount + "】"); } IDbCommand cmd = DataFactory.GetCommand(getInsertSql(entityInfo), conn); OrmHelper.SetParameters(cmd, "insert", obj, entityInfo); obj.Id = executeCmd(cmd, entityInfo); if (!DbContext.shouldTransaction()) { if (conn.State == ConnectionState.Open) { conn.Close(); conn.Dispose(); OrmHelper.clostCount++; LogManager.GetLogger("Class:System.ORM.Operation.InsertOperation Method:Insert").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】"); } } for (int i = 0; i < ilist.Count; i++) { ilist[i].AfterInsert(obj); } CacheUtil.CheckCountCache("insert", obj, entityInfo); result.Info = obj; CacheTime.updateTable(obj.GetType()); return(result); }
internal static IList Find(ConditionInfo condition) { IList results = ObjectPool.FindByQuery(condition); if (results != null) { return(results); } if ("*".Equals(condition.SelectedItem)) { condition.State.includeAll(); } else { condition.State.include(SqlBuilder.GetIncludeProperty(condition.SelectedItem)); } IList includeEntityPropertyList = condition.State.Includer.EntityPropertyList; IDbCommand cmd = DataFactory.GetCommand(condition.Sql, DbContext.getConnection(condition.State.EntityInfo)); foreach (String key in condition.Parameters.Keys) { DataFactory.SetParameter(cmd, key, condition.Parameters[key]); } Hashtable hashtable = new Hashtable(); IDataReader record = null; results = new ArrayList(); try { record = cmd.ExecuteReader(); while (record.Read()) { EntityPropertyUtil.Fill_EntityProperty_Ids(record, includeEntityPropertyList, ref hashtable); results.Add(FillUtil.Populate(record, condition.State)); } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); throw ex; } finally { if (!DbContext.shouldTransaction()) { if (cmd.Connection.State != ConnectionState.Closed) { cmd.Connection.Close(); cmd.Connection.Dispose(); OrmHelper.clostCount++; LogManager.GetLogger("Class:System.ORM.Operation.FindByOperation Method:Find").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】"); } } OrmHelper.CloseDataReader(record); } if (results.Count == 0) { return(results); } return(EntityPropertyUtil.setEntityProperty(condition.State, results, hashtable)); }
private void DoSales ( ExcelWorksheet worksheet, Dictionary <string, string> colDic, MasterMap mMap, DTO.ImportPost ip ) { int iStart = worksheet.Dimension.Start.Row; iStart = 2; int iEnd = GetLastRow(worksheet); if (iEnd > 0) { for (int i = iStart; i <= iEnd; i++) { var row = worksheet.Row(i); string warnings = ""; string requires = ""; var rec = new Sale(); foreach (string key in colDic.Keys) { try { var els = colDic[key].Split('|'); int ix = int.Parse(els[0]); string val = worksheet.GetValue(i, ix).ToString().Trim(); string pattern = els[1]; if (!String.IsNullOrEmpty(pattern)) { Regex regex = new Regex(pattern); Match match = regex.Match(val); if (match.Success) { val = match.Groups[1].Value; } } var colSpecs = mMap.Columns.First(o => o.ColumnName == key); if (!String.IsNullOrEmpty(val)) { dynamic realVal = null; switch (colSpecs.ColumnDataType) { case 1: realVal = val; break; case 2: val = Regex.Replace(val, "[^0-9.]", ""); var ppos = val.IndexOf('.'); if (ppos != -1) { val = val.Substring(0, ppos - 1); } realVal = Convert.ToInt64(val); break; case 3: val = Regex.Replace(val, "[^0-9.]", ""); realVal = Convert.ToDouble(val); break; case 4: DateTime realDT; if (DateTime.TryParse(val, out realDT)) { realVal = realDT; } if (realVal == null) { long ldate = long.Parse(val); realVal = DateTime.FromOADate(ldate); } break; case 5: realVal = OrmHelper.IsTrue(val); break; case 6: val = Regex.Replace(val, "[^0-9.]", ""); realVal = Decimal.Parse(val); break; } if (realVal != null) { OrmHelper.SetPropertyValue <Sale>(ref rec, key, realVal); } } } catch { warnings += $"'{key}',"; } } bool isFubar = false; foreach (var col in mMap.Columns) { if (col.Required) { dynamic realVal = OrmHelper.GetPropertyValue <Sale>(rec, col.ColumnName); if (realVal == null) { requires += $"'{col.ColumnName}',"; isFubar = true; } } } if (!isFubar) { rec.ImportId = ip.ImportId; rec.Row = i; rec.Sheet = ip.SheetNo; OrmHelper.SetAuditColumns <Sale>(ref rec, true, ip.PersonId); _db.Sale.Add(rec); } if (isFubar || warnings.Length > 0) { if (isFubar) { ip.SkipRows++; } if (warnings.Length > 0) { ip.WarnRows++; } string errInfo = "{"; errInfo += "warns:[" + warnings.TrimEnd(',') + "],"; errInfo += "skips:[" + requires.TrimEnd(',') + "]"; errInfo += "}"; var ie = new ImportError() { ImportId = ip.ImportId, Status = isFubar ? 1 : 0, Row = i, Sheet = ip.SheetNo, Errors = errInfo }; OrmHelper.SetAuditColumns <ImportError>(ref ie, true, ip.PersonId); _db.ImportError.Add(ie); } } } }
private static IEntity findById_Private(int id, ObjectInfo state) { if (id < 0) { return(null); } IEntity result = null; SqlBuilder sh = new SqlBuilder(state.EntityInfo); processIncluder(state.Includer); String sql = sh.GetFindById(id, state.Includer.SelectedProperty); var conn = DbContext.getConnection(state.EntityInfo); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); OrmHelper.initCount++; LogManager.GetLogger("Class:System.ORM.Operation.FindByIdOperation Method:findById_Private").Info("数据库连接已开启【" + OrmHelper.initCount + "】"); } IDbCommand cmd = DataFactory.GetCommand(sql, conn); IList list = new ArrayList(); IDataReader rd = null; try { rd = cmd.ExecuteReader(); while (rd.Read()) { list.Add(FillUtil.Populate(rd, state)); } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); throw ex; } finally { if (!DbContext.shouldTransaction()) { if (conn.State != ConnectionState.Closed) { conn.Close(); conn.Dispose(); OrmHelper.clostCount++; LogManager.GetLogger("Class:System.ORM.Operation.FindByIdOperation Method:findById_Private").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】"); } } OrmHelper.CloseDataReader(rd); } if (list.Count > 0) { result = list[0] as IEntity; } result = setEntityProperty(result, id, state); return(result); }