Esempio n. 1
0
 private void GatherChildrenID(MDataTable dt, string parentID, StringBuilder sb, string parentName = "ParentID")
 {
     if (!string.IsNullOrEmpty(parentID))
     {
         MDataRowCollection rows = dt.FindAll(parentName + "='" + parentID + "'");
         if (rows != null)
         {
             string id = string.Empty;
             foreach (MDataRow row in rows)
             {
                 id = row.Get <string>(0);
                 sb.Append("'" + id + "',");
                 GatherChildrenID(dt, id, sb, parentName);
             }
         }
     }
 }
Esempio n. 2
0
 public static List<MDataRow> FindAll(MDataTable table, object whereObj)
 {
     if (table != null && table.Rows.Count > 0)
     {
         if (Convert.ToString(whereObj).Trim() == "")
         {
             return table.Rows;
         }
         string whereStr = SqlFormat.GetIFieldSql(whereObj);
         string orderby;
         SplitWhereOrderby(ref whereStr, out orderby);
         TFilter[] filters = GetTFilter(whereStr, table.Columns);
         List<MDataRow> rows = table.Rows;
         if (filters.Length > 0)
         {
             rows = table.Rows.FindAll(delegate(MDataRow row)
              {
                  return CompareMore(row, filters);
              }
              );
         }
         filters = null;
         if (!string.IsNullOrEmpty(orderby) && rows.Count > 1)//进行数组排序
         {
             MDataRowCollection sortRows = new MDataRowCollection();
             sortRows.AddRange(rows);
             sortRows.Sort(orderby);
             return sortRows;
         }
         return rows;
     }
     return null;
 }
Esempio n. 3
0
        /// <summary>
        /// 批量更新或插入。
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="excelRow"></param>
        /// <returns></returns>
        public static bool AcceptChanges(MDataTable dt, MDataRow excelRow, string objName = null)
        {
            if (excelRow == null)
            {
                MDataTable dtImportUnique = GridConfig.GetList(objName, GridConfig.SelectType.ImportUnique);
                string[]   names          = null;
                if (dtImportUnique != null && dtImportUnique.Rows.Count > 0)
                {
                    names = new String[dtImportUnique.Rows.Count];
                    for (int i = 0; i < dtImportUnique.Rows.Count; i++)
                    {
                        names[i] = dtImportUnique.Rows[i].Get <string>(Config_Grid.Field);
                    }
                }
                return(dt.AcceptChanges(AcceptOp.Auto, CrossDb.GetConn(dt.TableName), names));
            }
            bool result = true;

            //获取相关配置
            string[]   tables      = excelRow.Get <string>(Config_Excel.TableNames).Split(',');
            MDataTable configTable = GetExcelInfo(excelRow.Get <string>(Config_Excel.ExcelID));

            Dictionary <string, string> rowPrimaryValue   = new Dictionary <string, string>(); //存档每个表每行的主键值。
            Dictionary <string, string> wherePrimaryValue = new Dictionary <string, string>(); //存档where条件对应的主键值。
            int acceptType = excelRow.Get <int>(Config_Excel.AcceptType);

            using (MAction action = new MAction(CrossDb.GetEnum(tables[0])))
            {
                action.SetAopState(AopOp.CloseAll);
                action.BeginTransation();
                AppConfig.Debug.OpenDebugInfo = false;
                IExcelConfig excelConfigExtend = ExcelConfigFactory.GetExcelConfigExtend();
                foreach (var table in tables)
                {
                    GC.Collect();//后面的Fill查询代码循环上万次会增长太多内存,提前调用,能降低内存。
                    action.ResetTable(table);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        action.Data.Clear();
                        var row = dt.Rows[i];
                        foreach (var cell in row)                                                                    //遍历所有数据行
                        {
                            if (cell.Struct.TableName != null && cell.Struct.TableName.ToLower() == table.ToLower()) //过滤出属于本表的字段。
                            {
                                string[] items      = cell.ColumnName.Split('.');
                                string   columnName = items[items.Length - 1];
                                action.Set(columnName, cell.Value);
                            }
                        }


                        #region 检测是否需要插入外键。
                        MDataTable foreignTable = configTable.FindAll("TableName='" + table + "' and IsForeignkey=1");
                        if (foreignTable != null)
                        {
                            foreach (var foreignRow in foreignTable.Rows)
                            {
                                string formatter  = foreignRow.Get <string>("Formatter", "").Trim('.');
                                string fTableName = foreignRow.Get <string>("ForeignTable");
                                if (string.IsNullOrEmpty(formatter))
                                {
                                    //获取主键外值键
                                    string key = fTableName + i;
                                    if (rowPrimaryValue.ContainsKey(key))
                                    {
                                        string value = rowPrimaryValue[key];
                                        action.Set(foreignRow.Get <string>("Field"), value);
                                    }
                                }
                                else // 从其它自定义列取值。
                                {
                                    MDataCell cell = row[formatter];
                                    cell = cell ?? row[fTableName + "." + formatter];
                                    if (cell != null)
                                    {
                                        action.Set(foreignRow.Get <string>("Field"), cell.Value);
                                    }
                                }
                            }
                            foreignTable = null;
                        }
                        #endregion


                        #region //获取唯一联合主键,检测是否重复

                        string where = string.Empty;
                        MDataRowCollection rowList = configTable.FindAll("TableName='" + table + "' and IsUnique=1");
                        if (rowList != null && rowList.Count > 0)
                        {
                            bool             isUniqueOr = excelRow.Get <bool>(Config_Excel.WhereType);
                            List <MDataCell> cells      = new List <MDataCell>();
                            StringBuilder    errText    = new StringBuilder();
                            int errorCount = 0;
                            foreach (var item in rowList)
                            {
                                var cell = action.Data[item.Get <string>(Config_ExcelInfo.Field)];
                                if (cell != null)
                                {
                                    if (cell.IsNullOrEmpty) // 唯一主键是必填写字段
                                    {
                                        errorCount++;
                                        errText.Append("[" + LangConst.The + "" + (i + 1) + LangConst.Row + "]:" + cell.Struct.ColumnName + "[" + cell.Struct.Description + "]" + LangConst.CantBeEmpty + "!\r\n");
                                    }
                                    else
                                    {
                                        cells.Add(cell);
                                    }
                                }
                            }
                            if (errorCount > 0)
                            {
                                if (!isUniqueOr || errorCount == rowList.Count)
                                {
                                    result         = false;
                                    dt.DynamicData = new Exception(errText.ToString());
                                    goto err;
                                }
                            }

                            MDataCell[] item2s = cells.ToArray();
                            where   = action.GetWhere(!isUniqueOr, item2s);
                            item2s  = null;
                            rowList = null;
                        }
                        if (!string.IsNullOrEmpty(where))
                        {
                            MDataRow data = action.Data.Clone();
                            action.SetSelectColumns(action.Data.PrimaryCell.ColumnName);
                            if (action.Fill(where))//根据条件查出主键ID (数据被清空)
                            {
                                string key = table + where;
                                if (wherePrimaryValue.ContainsKey(key))
                                {
                                    rowPrimaryValue.Add(table + i, wherePrimaryValue[key]);//记录上一个主键值。
                                }
                                else
                                {
                                    rowPrimaryValue.Add(table + i, action.Get <string>(action.Data.PrimaryCell.ColumnName)); //记录上一个主键值。
                                }
                                action.Data.LoadFrom(data, RowOp.IgnoreNull, false);                                         //还原数据。
                                if (action.Data.GetState() == 2 && acceptType != 1)                                          //排除掉仅插入选项
                                {
                                    ExcelResult eResult = excelConfigExtend.BeforeUpdate(action.Data, row);
                                    if (eResult == ExcelResult.Ignore || (eResult == ExcelResult.Default && action.Update(where)))
                                    {
                                        continue;//已经存在了,更新,准备下一条。
                                    }
                                    else
                                    {
                                        result         = false;
                                        dt.DynamicData = new Exception("[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo);
                                        goto err;
                                    }
                                }
                                else
                                {
                                    continue;//已经存在了,同时没有可更新字段
                                }
                            }
                            else if (action.RecordsAffected == -2)//产生错误信息,发生异常
                            {
                                result         = false;
                                dt.DynamicData = new Exception("[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo);
                                goto err;
                            }
                        }
                        #endregion

                        if (action.Data.GetState() == 0 || acceptType == 2) //仅更新则跳过插入
                        {
                            continue;                                       //没有可映射插入的列。
                        }

                        //插入前,调用函数(插入特殊主键等值)
                        string      errMsg;
                        ExcelResult excelResult = excelConfigExtend.BeforeInsert(action.Data, row, out errMsg);
                        if (excelResult == ExcelResult.Ignore)
                        {
                            continue;
                        }

                        if (excelResult == ExcelResult.Error || !action.Insert(InsertOp.ID))
                        {
                            result = false;
                            action.RollBack();
                            if (string.IsNullOrEmpty(errMsg))
                            {
                                errMsg = "[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo;
                            }
                            dt.DynamicData = new Exception(errMsg);
                            excelConfigExtend.OnInsertError(errMsg, dt);
                            goto err;
                        }
                        //插入后事件(可以触发其它事件)
                        excelConfigExtend.AfterInsert(action.Data, row, i == dt.Rows.Count - 1);
                        string primaryKey = action.Get <string>(action.Data.PrimaryCell.ColumnName);
                        rowPrimaryValue.Add(table + i, primaryKey);//记录上一个主键值。
                        if (!wherePrimaryValue.ContainsKey(table + where))
                        {
                            wherePrimaryValue.Add(table + where, primaryKey);
                        }
                    }
                }
err:
                action.EndTransation();
                excelConfigExtend.Dispose();
            }
            return(result);
        }
Esempio n. 4
0
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            MDataTable dt = null;
            #region 类型判断

           
            if (target is MDataTable)
            {
                dt = target as MDataTable;
            }
            else if (target is MDataRow)
            {
                dt = ((MDataRow)target).ToTable();
            }
            else if (target is MDataColumn)
            {
                dt = ((MDataColumn)target).ToTable();
            }
            else if (target is MDataRowCollection)
            {
                dt = target as MDataRowCollection;
            }
            else if (target is DataRow)
            {
                MDataRow row = target as DataRow;
                dt = row.ToTable();
            }
            else if (target is DataColumnCollection)
            {
                MDataColumn mdc = target as DataColumnCollection;
                dt = mdc.ToTable();
            }
            else if (target is DataRowCollection)
            {
                MDataRowCollection rows = target as DataRowCollection;
                dt = rows;
            }
            else if (target is NameObjectCollectionBase)
            {
                dt = MDataTable.CreateFrom(target as NameObjectCollectionBase);
            }
            else if (target is IEnumerable)
            {
                dt = MDataTable.CreateFrom(target as IEnumerable);
            }
            else
            {
                dt = MDataTable.CreateFrom(target);
                if (dt == null)
                {
                    MDataRow row = MDataRow.CreateFrom(target);
                    if (row != null)
                    {
                        dt = row.ToTable();
                    }
                }
            }
            #endregion
            dt = Format(dt);
            if (dt != null)
            {
                base.GetData(dt.ToDataTable(), outgoingData);
            }
            else
            {

                base.GetData(new DataTable("Empty Table"), outgoingData);
            }
        }
Esempio n. 5
0
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            MDataRowCollection mrc = target as DataRowCollection;

            base.GetData(mrc, outgoingData);
        }
Esempio n. 6
0
        public static MDataRow FindRow(MDataTable table, object whereObj)
        {
            if (table.Rows.Count > 0)
            {
                if (Convert.ToString(whereObj).Trim() == "")
                {
                    return table.Rows[0];
                }
                string whereStr = SqlFormat.GetIFieldSql(whereObj);
                string orderby;
                SplitWhereOrderby(ref whereStr, out orderby);
                MDataRowCollection sortRows = null;
                if (!string.IsNullOrEmpty(orderby) && table.Rows.Count > 1)//进行数组排序
                {
                    sortRows = new MDataRowCollection();
                    sortRows.AddRange(table.Rows);
                    sortRows.Sort(orderby);
                }
                TFilter[] filters = GetTFilter(whereStr, table.Columns);

                if (filters.Length > 0)
                {
                    if (sortRows == null)
                    {
                        sortRows = table.Rows;
                    }
                    for (int i = 0; i < sortRows.Count; i++)
                    {
                        if (CompareMore(sortRows[i], filters))
                        {
                            return sortRows[i];
                        }
                    }
                }

            }
            return null;
        }