/// <summary> /// 通过主键获取对应明细的数据。 /// </summary> /// <param name="baseRule">指定操作的业务类</param> /// <param name="dataInDocType">指定的数据类型</param> /// <param name="mainKeyValue">主键</param> /// <returns></returns> public System.Data.DataSet GetObjectsByForeingKeyAsDs(IBaseRule baseRule, object dataInDocType, object mainKeyValue) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); System.Data.Common.DbCommand[] cmds = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_GET_BY_FOREING_KEY, mainKeyValue); if (cmds.Length != 1) { throw new MB.RuleBase.Exceptions.SelectSqlXmlConfigException(mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_GET_BY_FOREING_KEY); } System.Data.Common.DbCommand cmd = cmds[0]; DataSet ds = null; try { string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd); MB.Util.TraceEx.Write("正在执行:" + cmdMsg); ds = new DatabaseExecuteHelper(_QueryBehavior).ExecuteDataSet(db, cmd); } catch (Exception ex) { throw new MB.RuleBase.Exceptions.DatabaseExecuteException("GetObjectsByForeingKey 出错!", ex); } return(ds); }
/// <summary> /// 批量创建实体对象。 /// </summary> /// <param name="baseRule"></param> /// <param name="dataInDocType"></param> /// <param name="createCount"></param> /// <returns></returns> public IList CreateNewEntityBatch(IBaseRule baseRule, object dataInDocType, int createCount) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } Type entityType = mappingAtt.EntityType; if (string.Compare(entityType.FullName, "System.Object", true) == 0) { if (mappingAtt.EntityType == null) { throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 中的:" + dataInDocType.GetType() + " 的数据值:" + dataInDocType.ToString() + " 在配置ObjectDataMapping时需要配置 EntityType", MB.Util.APPMessageType.SysErrInfo); } } List <object> lstData = new List <object>(); int id = 0; //判断是否为自增列 if (mappingAtt.KeyIsSelfAdd) { id = MB.Orm.Persistence.EntityIdentityHelper.NewInstance.GetEntityIdentity(mappingAtt.MappingTableName, createCount); } for (int i = 0; i < createCount; i++) { object entity = MB.Util.DllFactory.Instance.CreateInstance(entityType); //判断是否为自增列 if (id > 0) { MB.Util.MyReflection.Instance.InvokePropertyForSet(entity, mappingAtt.KeyName, id++); } if (entity.GetType().IsSubclassOf(typeof(MB.Orm.Common.BaseModel))) { (entity as MB.Orm.Common.BaseModel).EntityState = EntityState.New; } //设置默认值 MB.Orm.Mapping.ModelMappingInfo mappingInfo = MB.Orm.Mapping.AttMappingManager.Instance.GetModelMappingInfo(entityType); foreach (MB.Orm.Mapping.FieldPropertyInfo colProperty in mappingInfo.FieldPropertys.Values) { if (colProperty.DefaultValue == null) { continue; } System.Reflection.PropertyInfo proInfo = entityType.GetProperty(colProperty.PropertyName); proInfo.SetValue(entity, colProperty.DefaultValue, null); } lstData.Add(entity); } return(lstData); }
/// <summary> /// 根据数据类型和过滤条件返回需要的数据。 /// </summary> /// <param name="baseRule">指定操作的业务类。</param> /// <param name="dataInDocType">指定的数据类型。</param> /// <param name="whereFilters">过滤条件</param> /// <param name="otherParamValues">其它附加的过滤条件</param> /// <returns>满足条件的DataSet 类型数据</returns> public System.Data.DataSet GetObjectAsDataSet(IBaseQueryRule baseRule, object dataInDocType, QueryParameterInfo[] parInfos, params object[] parValues) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } string sqlName = string.IsNullOrEmpty(mappingAtt.XmlCfgSelectSqlName) ? MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_OBJECT : mappingAtt.XmlCfgSelectSqlName; MB.Orm.Mapping.QueryParameterMappings queryMappings = baseRule.QueryParamMapping; if (queryMappings == null) { queryMappings = MB.Orm.Mapping.Xml.SqlConfigHelper.Instance.GetSqlQueryParamMappings(mappingAtt.MappingXmlFileName, sqlName); } string sqlFilter = MB.Orm.DbSql.SqlShareHelper.Instance.QueryParametersToSqlString(queryMappings, parInfos); Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); ArrayList paramValues = new ArrayList(); if (parValues != null && parValues.Length > 0) { foreach (object v in parValues) { paramValues.Add(v); } } paramValues.Add(sqlFilter); System.Data.Common.DbCommand[] cmds = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, mappingAtt.MappingXmlFileName, sqlName, paramValues.ToArray()); if (cmds.Length != 1) { throw new MB.RuleBase.Exceptions.SelectSqlXmlConfigException(mappingAtt.MappingXmlFileName, sqlName); } System.Data.Common.DbCommand cmd = cmds[0]; DataSet ds = null; try { MB.Util.TraceEx.Write("正在执行:" + MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd)); ds = new DatabaseExecuteHelper(_QueryBehavior).ExecuteDataSet(db, cmd); } catch (Exception ex) { throw new MB.RuleBase.Exceptions.DatabaseExecuteException("GetObjectAsDataSet 出错!", ex); } return(ds); }
/// <summary> /// 根据键值直接执行业务类中指定数据类型的数据。 /// 特殊说明: 暂时先在这里进行服务的提交处理,以后需要进行修改。 /// </summary> /// <param name="baseRule">指定操作的业务类。</param> /// <param name="dataInDocType">数据在业务类的中数据类型。</param> /// <param name="key">指定需要删除的键值。</param> /// <returns>返回受影响的行。</returns> public int DeletedImmediate(IBaseRule baseRule, object dataInDocType, object key) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } // Create the Database object, using the default database service. The // default database service is determined through configuration. Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); System.Data.Common.DbCommand[] cmds = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_DELETE_OBJECT, key); int count = 0; //using (DbConnection connection = db.CreateConnection()) { // connection.Open(); try { foreach (System.Data.Common.DbCommand cmd in cmds) { string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd); MB.Util.TraceEx.Write("正在执行:" + cmdMsg); using (new Util.MethodTraceWithTime(true, cmdMsg)) { count = db.ExecuteNonQuery(cmd); } } } catch (Exception ex) { //throw new MB.RuleBase.Exceptions.DatabaseExecuteException("DeletedImmediate 出错!", ex); throw; } finally { //if (connection.State == System.Data.ConnectionState.Open) // connection.Close(); try { foreach (System.Data.Common.DbCommand cmd in cmds) { cmd.Dispose(); } } catch { } } return(count); // } }
/// <summary> /// 获取指定类型新创建对象的自增列ID。 /// </summary> /// <param name="dataInDocType">在单据中的数据类型,默认为主表的数据。</param> /// <param name="count">获取ID 的个数</param> /// <returns>返回第一个对象的ID,其它的加1 就可以,但最大值不能超过返回值 + count -1</returns> public virtual int GetCreateNewEntityIds(int dataInDocType, int count) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(ConvertDataInDocType(dataInDocType)); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(ConvertDataInDocType(dataInDocType)); } //不是自增加列 不需要返回自增列的ID if (!mappingAtt.KeyIsSelfAdd) { return(0); } return(MB.Orm.Persistence.EntityIdentityHelper.NewInstance.GetEntityIdentity(mappingAtt.MappingTableName, count)); }
/// <summary> /// 根据指定类型获取满足条件的实体对象。 /// </summary> /// <typeparam name="T">从MB.Orm.Common.BaseModel 中继承的数据对象类型。</typeparam> /// <param name="baseRule">获取实体对象集合的业务类。</param> /// <param name="dataInDocType">在业务类中的数据类型。</param> /// <param name="filter">过滤条件。</param> /// <returns>指定类型的集合类。</returns> public List <T> GetObjects <T>(IBaseQueryRule baseRule, object dataInDocType, QueryParameterInfo[] parInfos, params object[] parValues) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } string sqlName = string.IsNullOrEmpty(mappingAtt.XmlCfgSelectSqlName) ? MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_OBJECT : mappingAtt.XmlCfgSelectSqlName; MB.Orm.Mapping.QueryParameterMappings queryMappings = baseRule.QueryParamMapping; if (queryMappings == null) { queryMappings = MB.Orm.Mapping.Xml.SqlConfigHelper.Instance.GetSqlQueryParamMappings(mappingAtt.MappingXmlFileName, sqlName); } string sqlFilter = MB.Orm.DbSql.SqlShareHelper.Instance.QueryParametersToSqlString(queryMappings, parInfos); Type entityType = typeof(T); if (string.Compare(entityType.FullName, "System.Object", true) == 0) { if (mappingAtt.EntityType == null) { throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 中的:" + dataInDocType.GetType() + " 的数据值:" + dataInDocType.ToString() + " 在配置ObjectDataMapping时需要配置 EntityType", MB.Util.APPMessageType.SysErrInfo); } entityType = mappingAtt.EntityType; } List <object> pars = new List <object>(); if (parValues != null && parValues.Length > 0) { foreach (object p in parValues) { pars.Add(p); } } pars.Add(sqlFilter); //以后需要增加是否通过XML 配置还是根据实体自动生成。 return(new DatabaseExcuteByXmlHelper(_QueryBehavior).GetObjectsByXml <T>(entityType, mappingAtt.MappingXmlFileName, sqlName, pars.ToArray())); }
/// <summary> /// 获取数据对象的主键。 /// </summary> /// <param name="baseRule"></param> /// <param name="dataInfo"></param> /// <returns></returns> public object GetObjectKeyValue(IBaseRule baseRule, ObjectDataInfo dataInfo) { string keyName = null; if (dataInfo.DataInDocType != null) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInfo.DataInDocType); if (mappingAtt != null) { keyName = mappingAtt.KeyName; } } bool isEntity = dataInfo.ObjectData.GetType().IsSubclassOf(typeof(MB.Orm.Common.BaseModel)); if (string.IsNullOrEmpty(keyName) && isEntity) { MB.Orm.Mapping.Att.ModelMapAttribute tattr = Attribute.GetCustomAttribute(dataInfo.ObjectData.GetType(), typeof(MB.Orm.Mapping.Att.ModelMapAttribute)) as MB.Orm.Mapping.Att.ModelMapAttribute; string[] keys = tattr.PrimaryKeys; if (keys != null && keys.Length > 0) { MB.Util.TraceEx.Assert(keys.Length > 1, "业务类:" + baseRule.GetType().FullName + " 主表对象的键值配置不能存在联合主键!"); } keyName = keys[0]; } if (string.IsNullOrEmpty(keyName)) { throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 的主表对象的主键信息没有配置!", MB.Util.APPMessageType.SysErrInfo); } if (isEntity) { return(MB.Util.MyReflection.Instance.InvokePropertyForGet(dataInfo.ObjectData, keyName)); } else if ((dataInfo.ObjectData as DataRow) != null) { return((dataInfo.ObjectData as DataRow)[keyName]); } else { throw new MB.Util.APPException("获取业务类:" + baseRule.GetType().FullName + " 的主表对象的键值有误!", MB.Util.APPMessageType.SysErrInfo); } }
/// <summary> /// 通过主键获取对应明细的数据。 /// </summary> /// <typeparam name="T">从MB.Orm.Common.BaseModel 中继承的数据对象类型。</typeparam> /// <param name="baseRule">指定操作的业务类</param> /// <param name="dataInDocType">指定的数据类型</param> /// <param name="mainKeyValue">主键</param> /// <returns></returns> public List <T> GetObjectsByForeingKey <T>(IBaseRule baseRule, object dataInDocType, object mainKeyValue) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } Type entityType = typeof(T); if (string.Compare(entityType.FullName, "System.Object", true) == 0) { if (mappingAtt.EntityType == null) { throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 中的:" + dataInDocType.GetType() + " 的数据值:" + dataInDocType.ToString() + " 在配置ObjectDataMapping时需要配置 EntityType", MB.Util.APPMessageType.SysErrInfo); } entityType = mappingAtt.EntityType; } return(DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml <T>(entityType, mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_GET_BY_FOREING_KEY, mainKeyValue)); }
/// <summary> /// 根据数据类型检查指定的值在数据库中是否已经存在 /// </summary> /// <param name="dataInDocType">需要进行检查的数据类型</param> /// <param name="entity">需要检查的实体对象</param> /// <param name="checkPropertys">需要检查的属性名称</param> /// <returns>true 或 false</returns> public bool CheckValueIsExists(object dataInDocType, object entity, string[] checkPropertys) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } string tableName = mappingAtt.MappingTableName; object keyValue = MB.Util.MyReflection.Instance.InvokePropertyForGet(entity, mappingAtt.KeyName); if (keyValue == null) { keyValue = string.Empty; } string sql = string.Format("SELECT 1 FROM {0} WHERE ROWNUM <=1 AND {1}<>'{2}' AND ", tableName, mappingAtt.KeyName, keyValue.ToString().Replace("'", "''")); string where = string.Empty; MB.Orm.Enums.DatabaseType dbaseType = MB.Orm.Persistence.DatabaseHelper.CreateDatabaseType(); foreach (string name in checkPropertys) { if (!string.IsNullOrEmpty(where)) { where += " AND "; } object checkVal = MB.Util.MyReflection.Instance.InvokePropertyForGet(entity, name); Type type = MB.Util.MyReflection.Instance.GetPropertyType(entity, name); if (type == typeof(string)) //如果是string { string checkValStr = checkVal as string; if (string.IsNullOrEmpty(checkValStr)) { where += string.Format(" ({0} = '' OR {0} IS NULL) ", name); } else { where += string.Format("{0} = '{1}'", name, checkVal.ToString().Replace("'", "''")); } } else if (type == typeof(DateTime)) { //如果是日期类型,日期类型只检查到 DateTime checkValueUnBoxed = (DateTime)checkVal; if (dbaseType == DatabaseType.Oracle) { where += string.Format("TO_CHAR({0}, 'YYYY-MM-DD') = '{1}'", name, checkValueUnBoxed.ToString("yyyy-MM-dd").Replace("'", "''")); } else { where += string.Format("{0} = '{1}'", name, checkValueUnBoxed.ToString("yyyy-MM-dd").Replace("'", "''")); } } else if (type == typeof(DateTime?)) { if (checkVal == null) { where += string.Format(" {0} IS NULL ", name); } else { DateTime checkValueUnBoxed = (DateTime)checkVal; if (dbaseType == DatabaseType.Oracle) { //如果是日期类型,日期类型只检查到 where += string.Format("TO_CHAR({0}, 'YYYY-MM-DD') = '{1}'", name, checkValueUnBoxed.ToString("yyyy-MM-dd").Replace("'", "''")); } else { where += string.Format("{0} = '{1}'", name, checkValueUnBoxed.ToString("yyyy-MM-dd").Replace("'", "''")); } } } else { if (checkVal == null) { where += string.Format(" {0} IS NULL ", name); } else { where += string.Format("{0} = '{1}'", name, checkVal.ToString().Replace("'", "''")); } } } Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); sql += where; DbCommand dbCmd = db.GetSqlStringCommand(sql); object val = DatabaseExecuteHelper.NewInstance.ExecuteScalar(db, dbCmd); if (val != null) { return(MB.Util.MyConvert.Instance.ToBool(val)); } else { return(false); } }
/// <summary> /// 根据键值获取包含值的实体对象。 /// </summary> /// <typeparam name="T">从MB.Orm.Common.BaseModel 中继承的数据对象类型。</typeparam> /// <param name="baseRule">获取实体对象集合的业务类。</param> /// <param name="dataInDocType">在业务类中的数据类型。</param> /// <param name="keyValue">需要获取实体键值。</param> /// <returns>返回指定类型的实体对象。</returns> public T GetObjectByKey <T>(IBaseRule baseRule, object dataInDocType, object keyValue) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); System.Data.Common.DbCommand[] cmds = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_BY_KEY, keyValue); if (cmds.Length != 1) { throw new MB.RuleBase.Exceptions.SelectSqlXmlConfigException(mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_BY_KEY); } System.Data.Common.DbCommand cmd = cmds[0]; Type entityType = typeof(T); if (string.Compare(entityType.FullName, "System.Object", true) == 0) { if (mappingAtt.EntityType == null) { throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 中的:" + dataInDocType.GetType() + " 的数据值:" + dataInDocType.ToString() + " 在配置ObjectDataMapping时需要配置 EntityType", MB.Util.APPMessageType.SysErrInfo); } entityType = mappingAtt.EntityType; } bool isBaseModelSub = entityType.IsSubclassOf(typeof(BaseModel)); MB.Orm.Mapping.ModelMappingInfo modelMapping = MB.Orm.Mapping.AttMappingManager.Instance.GetModelMappingInfo(entityType); object entity = MB.Util.DllFactory.Instance.CreateInstance(entityType); string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd); MB.Util.TraceEx.Write("正在执行:" + cmdMsg); using (new Util.MethodTraceWithTime(cmdMsg)) { using (IDataReader reader = db.ExecuteReader(cmd)) { try { DataTable dtReader = reader.GetSchemaTable(); while (reader.Read()) { foreach (MB.Orm.Mapping.FieldPropertyInfo proInfo in modelMapping.FieldPropertys.Values) { if (dtReader.Select(string.Format("ColumnName='{0}'", proInfo.FieldName)).Length <= 0) { continue; } if (reader[proInfo.FieldName] != System.DBNull.Value) { MB.Util.MyReflection.Instance.InvokePropertyForSet(entity, proInfo.PropertyName, reader[proInfo.FieldName]); } } break; } } catch (Exception ex) { throw new MB.RuleBase.Exceptions.DatabaseExecuteException("执行" + baseRule.GetType().FullName + "GetObjectByKey<T> 出错!", ex); } finally { } } } if (isBaseModelSub) { MB.Orm.Common.BaseModel temp = entity as MB.Orm.Common.BaseModel; //if (temp == null) // throw new MB.Util.APPException(string.Format("所有的数据实体对象都必须从MB.Orm.Common.BaseModel 继承,请检查{0}", entity.GetType())); temp.EntityState = EntityState.Persistent; } return((T)entity); }
/// <summary> /// 从DataSet 中创建可以进行数据库操作的DBCommand。 /// </summary> /// <param name="db"></param> /// <param name="baseRule"></param> /// <param name="dsData"></param> /// <param name="dataInDocType"></param> /// <returns></returns> public IList <EntityDbCommandInfo> CreateCmdsFromDataSet(Database db, IBaseRule baseRule, DataSet dsData, object foreingKeyValue, object dataInDocType) { List <EntityDbCommandInfo> cmds = new List <EntityDbCommandInfo>(); ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); MB.Orm.Enums.OperationType opts = MB.Orm.Enums.OperationType.Insert | MB.Orm.Enums.OperationType.Update; if (mappingAtt.DeleteNotInIds) { opts = opts | MB.Orm.Enums.OperationType.DeleteNotIn; } else { opts = opts | MB.Orm.Enums.OperationType.Delete; } MB.Orm.Persistence.PersistenceManagerHelper persistenceManager = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance; Dictionary <MB.Orm.Enums.OperationType, MB.Orm.DbSql.SqlString[]> sqlLib = MB.Orm.Mapping.Xml.SqlConfigHelper.Instance.GetObjectStandardEditSql(mappingAtt.MappingXmlFileName, opts); DataRow[] drsData = dsData.Tables[0].Select(); if (sqlLib.ContainsKey(OperationType.DeleteNotIn) && (foreingKeyValue != null && foreingKeyValue != System.DBNull.Value)) { EntityDbCommandInfo[] cmdDeletes = persistenceManager.CreateDeleteNotInDbCommand(db, sqlLib[OperationType.DeleteNotIn], drsData, mappingAtt.KeyName, foreingKeyValue); cmds.AddRange(cmdDeletes); } StringBuilder sqlB = new StringBuilder(); foreach (DataRow dr in drsData) { //空行跳过不进行处理 bool b = MB.Orm.Common.ValueValidated.Instance.RowIsNull(dr); if (b) { continue; } switch (dr.RowState) { case System.Data.DataRowState.Added: //增加 if (!sqlLib.ContainsKey(OperationType.Insert)) { continue; } if (!string.IsNullOrEmpty(mappingAtt.ForeingKeyName) && foreingKeyValue != null && dr.Table.Columns.Contains(mappingAtt.ForeingKeyName) && (dr[mappingAtt.ForeingKeyName] == System.DBNull.Value)) { dr[mappingAtt.ForeingKeyName] = foreingKeyValue; } DbCommand[] cmdAdds = persistenceManager.CreateDbCommandByDataRow(db, sqlLib[OperationType.Insert], dr); foreach (DbCommand ad in cmdAdds) { cmds.Add(new EntityDbCommandInfo(dr, ad)); } // cmds.AddRange(cmdAdds); break; case System.Data.DataRowState.Modified: //修改 if (!sqlLib.ContainsKey(OperationType.Update)) { continue; } DbCommand[] cmdUpdates = persistenceManager.CreateDbCommandByDataRow(db, sqlLib[OperationType.Update], dr); foreach (DbCommand ud in cmdUpdates) { cmds.Add(new EntityDbCommandInfo(dr, ud)); } // cmds.AddRange(cmdUpdates); break; case System.Data.DataRowState.Deleted: //删除为直接删除,所以这里不进行处理。 break; case System.Data.DataRowState.Detached: default: break; } } return(cmds); }
/// <summary> /// 通过DataSet 直接存储到数据库,排除已经删除的行,对于需要删除的行请直接通过 DeletedImmediate 来进行。 /// 特殊说明: 暂时先在这里进行服务的提交处理,以后需要进行修改。 /// </summary> /// <param name="baseRule">当前需要操作的业务类。</param> /// <param name="dataInDocType">数据在业务类的中数据类型。</param> /// <param name="dsData">DataSet 类型数据。</param> /// <returns>返回受影响的行。</returns> public int SaveDataSetImmediate(IBaseRule baseRule, object dataInDocType, System.Data.DataSet dsData) { ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType); if (mappingAtt == null) { throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType); } // Create the Database object, using the default database service. The // default database service is determined through configuration. Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase(); IList <EntityDbCommandInfo> cmds = CreateCmdsFromDataSet(db, baseRule, dsData, null, dataInDocType); if (cmds.Count == 0) { return(0); } int count = 0; //using (DbConnection connection = db.CreateConnection()) { // connection.Open(); try { foreach (EntityDbCommandInfo cmd in cmds) { try { string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd.DbCommand); MB.Util.TraceEx.Write("正在执行:" + cmdMsg); using (new Util.MethodTraceWithTime(true, cmdMsg)) { count += db.ExecuteNonQuery(cmd.DbCommand); } } catch (Exception ex) { throw new MB.RuleBase.Exceptions.DatabaseExecuteException("SaveDataSetImmediate 出错!", ex); } } } catch (MB.RuleBase.Exceptions.DatabaseExecuteException dx) { throw; } catch (Exception exx) { throw; //throw new MB.RuleBase.Exceptions.DatabaseExecuteException("SaveDataSetImmediate 出错!", exx); } finally { //if (connection.State == System.Data.ConnectionState.Open) // connection.Close(); try { foreach (EntityDbCommandInfo cmd in cmds) { cmd.DbCommand.Dispose(); } } catch { } } return(count); // } }