小周的技术博客

困难是培养伟大心志的保姆,唯有这个冷酷的保姆才会不停地推着摇篮,培养一个勇敢、刚健的孩子。 ---------布赖恩特

Linq To SQL批量操作(更新,删除,插入)

本文来自 小周的技术博客 转载请注明;

本文地址:http://blog.lyttensoft.win/?id=59



以往项目的代码,做备份

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Data.Linq;
using System.Data;
using System.Data.Linq.Mapping;
using System.Reflection;

namespace WeiSite.ForData
{
    public static class DataBaseFunction
    {
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table">表</param>
        /// <param name="predicate">查询条件表达式</param>
        /// <returns>影响的行数</returns>
        public static int Delete<T>(T table, Expression<Func<T, bool>> predicate, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            //查询条件表达式转换成SQL的条件语句
            ConditionBuilder builder = new ConditionBuilder();
            builder.Build(predicate.Body);
            string sqlCondition = builder.Condition;
            string commandText = string.Empty;
            //SQL命令
            if (sqlCondition == "{0}")
            {
                commandText = string.Format("DELETE FROM {0}", tableName);
            }
            else
            {
                commandText = string.Format("DELETE FROM {0} WHERE {1}", tableName, sqlCondition);
            }


            //获取SQL参数数组 
            var args = builder.Arguments;
            //执行
            return dataContext.ExecuteCommand(commandText, args);
        }
        /// <summary>
        /// 批量添加 The same column
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public static int Insert<T>(T table, List<Dictionary<string, string>> InsertData, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            DbCommand command = dataContext.GetCommand(dataContext.GetTable<T>());
            Type tableType = typeof(T);
            string sql = string.Empty;
            string values = string.Empty;
            string field = string.Empty;
            List<string> sqlvalue = new List<string>();
            for (int i = 0; i < InsertData.Count(); i++)
            {
                Dictionary<string, string> insert = (Dictionary<string, string>)InsertData[i];
                values = string.Empty;
                foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
                {
                    //这里只对绑定列的属性进行赋值
                    if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
                    {
                        if (insert.ContainsKey(ProInfo.Name))
                        {
                            if (i == 0) field += ProInfo.Name + ",";
                            values += checkField(insert[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + ",";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(values))
                {
                    values = values.Remove(values.Length - 1);
                }
                sqlvalue.Add("(" + values + "),");
            }
            if (!string.IsNullOrEmpty(field))
            {
                field = field.Remove(field.Length - 1);
            }
            for (int i = 0; i < (sqlvalue.Count() / 1000 + ((sqlvalue.Count() % 1000) != 0 ? 1 : 0)); i++)
            {
                sql += " insert into " + tableName + " (" + field + ") values ";
                for (int j = 0; (i * 1000 + j) < sqlvalue.Count() && j < 1000; j++)
                {
                    sql += sqlvalue[i * 1000 + j].ToString().Trim();
                }
                if (!string.IsNullOrEmpty(sql))
                {
                    sql = sql.Remove(sql.Length - 1);
                }
            }
            //SQL命令
            //获取SQL参数数组 (包括查询参数和赋值参数)
            command.CommandText = sql;
            command.CommandTimeout = 1000 * 10;
            //执行 
            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    command.Connection.Open();
                }
                return command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
                command.Dispose();
            }
        }

        /// <summary>
        /// 批量添加 Different Fields
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public static int InsertDic<T>(T table, List<Dictionary<string, string>> InsertData, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            DbCommand command = dataContext.GetCommand(dataContext.GetTable<T>());
            Type tableType = typeof(T);
            string sql = string.Empty;
            string values = string.Empty;
            
            //List<string> sqlvalue = new List<string>();
            for (int i = 0; i < InsertData.Count(); i++)
            {
                Dictionary<string, string> insert = (Dictionary<string, string>)InsertData[i];
                string field = string.Empty;
                values = string.Empty;
                foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
                {
                    //这里只对绑定列的属性进行赋值
                    if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
                    {
                        if (insert.ContainsKey(ProInfo.Name))
                        {
                            field += ProInfo.Name + ",";
                            values += checkField(insert[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + ",";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(values))
                {
                    values = values.Remove(values.Length - 1);
                }
                values=("(" + values + ")");
                if (!string.IsNullOrEmpty(field))
                {
                    field = field.Remove(field.Length - 1);
                }
                sql += " insert into " + tableName + " (" + field + ") values "+values;
            }
          
            //for (int i = 0; i < (sqlvalue.Count() / 1000 + ((sqlvalue.Count() % 1000) != 0 ? 1 : 0)); i++)
            //{
            //    sql += " insert into " + tableName + " (" + field + ") values ";
            //    for (int j = 0; (i * 1000 + j) < sqlvalue.Count() && j < 1000; j++)
            //    {
            //        sql += sqlvalue[i * 1000 + j].ToString().Trim();
            //    }
            //    if (!string.IsNullOrEmpty(sql))
            //    {
            //        sql = sql.Remove(sql.Length - 1);
            //    }
            //}
            //SQL命令
            //获取SQL参数数组 (包括查询参数和赋值参数)
            command.CommandText = sql;
            command.CommandTimeout = 1000 * 10;
            //执行 
            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    command.Connection.Open();
                }
                return command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
                command.Dispose();
            }
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public static int Update<T>(List<Dictionary<string, string>> UpdateFields, List<Dictionary<string, string>> UpdateWheres, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            DbCommand command = dataContext.GetCommand(dataContext.GetTable<T>());
            Type tableType = typeof(T);
            string sql = string.Empty;
            string values = string.Empty;
            List<string> sqlvalue = new List<string>();
            for (int i = 0; i < UpdateFields.Count(); i++)
            {
                Dictionary<string, string> update = (Dictionary<string, string>)UpdateFields[i];
                Dictionary<string, string> updateId = (Dictionary<string, string>)UpdateWheres[i];
                values = string.Empty;
                string _where = string.Empty;
                foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
                {
                    //这里只对绑定列的属性进行赋值
                    if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
                    {
                        if (update.ContainsKey(ProInfo.Name))
                        {
                            values += ProInfo.Name + "=" + checkField(update[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + ",";
                        }
                        if (updateId.ContainsKey(ProInfo.Name))
                        {
                            _where += ProInfo.Name + "=" + checkField(updateId[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + " and ";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(values))
                {
                    values = values.Remove(values.Length - 1);
                }
                if (!string.IsNullOrEmpty(_where))
                {
                    _where = _where.Remove(_where.Length - 5);
                }
                sqlvalue.Add(values + " where " + _where);
            }

            for (int i = 0; i < (sqlvalue.Count() / 1000 + ((sqlvalue.Count() % 1000) != 0 ? 1 : 0)); i++)
            {
                for (int j = 0; (i * 1000 + j) < sqlvalue.Count() && j < 1000; j++)
                {
                    sql += " update " + tableName + " set   " + sqlvalue[i * 1000 + j].ToString().Trim();
                }
            }
            //SQL命令
            //获取SQL参数数组 (包括查询参数和赋值参数)
            command.CommandText = sql;
            command.CommandTimeout = 1000 * 10;
            //执行 
            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    command.Connection.Open();
                }
                return command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
                command.Dispose();
            }
        }


        /// <summary>
        /// 批量更新(更新条件所指向的数据为相同的值)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public static int Update<T>(Dictionary<string, string> UpdateField, List<Dictionary<string, string>> UpdateWheres, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            DbCommand command = dataContext.GetCommand(dataContext.GetTable<T>());
            Type tableType = typeof(T);
            string SqlExecString = string.Empty;

            List<string> UpdateSqls = new List<string>();
            for (int i = 0; i < UpdateWheres.Count(); i++)
            {
                Dictionary<string, string> updateWhere = (Dictionary<string, string>)UpdateWheres[i];
                string SetValues = string.Empty;
                string WhereString = string.Empty;

                foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
                {
                    //这里只对绑定列的属性进行赋值
                    if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
                    {
                        if (UpdateField.ContainsKey(ProInfo.Name))
                        {
                            SetValues += ProInfo.Name + "=" + checkField(UpdateField[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + ",";
                        }
                        if (updateWhere.ContainsKey(ProInfo.Name))
                        {
                            WhereString += ProInfo.Name + "=" + checkField(updateWhere[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + " and ";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(SetValues))
                {
                    SetValues = SetValues.Remove(SetValues.Length - 1);
                }
                if (!string.IsNullOrEmpty(WhereString))
                {
                    WhereString = WhereString.Remove(WhereString.Length - 5);
                }
                UpdateSqls.Add(SetValues + " where " + WhereString);
            }

            for (int i = 0; i < (UpdateSqls.Count() / 1000 + ((UpdateSqls.Count() % 1000) != 0 ? 1 : 0)); i++)
            {
                for (int j = 0; (i * 1000 + j) < UpdateSqls.Count() && j < 1000; j++)
                {
                    SqlExecString += " update " + tableName + " set   " + UpdateSqls[i * 1000 + j].ToString().Trim();
                }
            }
            //SQL命令
            //获取SQL参数数组 (包括查询参数和赋值参数)
            command.CommandText = SqlExecString;
            command.CommandTimeout = 1000 * 10;
            //执行 
            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    command.Connection.Open();
                }
                return command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
                command.Dispose();
            }
        }

        /// <summary>
        /// 批量更新(更新条件所指向的数据为相同的值)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        /// 

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public static int UpdateNew<T>(List<Dictionary<string, string>> UpdateFields, List<Dictionary<string, Dictionary<string, int>>> UpdateWheres, DataContext dataContext) where T : class
        {
            //获取表名
            string tableName = dataContext.Mapping.GetTable(typeof(T)).TableName;
            DbCommand command = dataContext.GetCommand(dataContext.GetTable<T>());
            Type tableType = typeof(T);
            string sql = string.Empty;
            string values = string.Empty;
            List<string> sqlvalue = new List<string>();
            for (int i = 0; i < UpdateFields.Count(); i++)
            {
                Dictionary<string, string> update = (Dictionary<string, string>)UpdateFields[i];
                Dictionary<string, Dictionary<string, int>> updateId = (Dictionary<string, Dictionary<string, int>>)UpdateWheres[i];
                values = string.Empty;
                string _where = string.Empty;
                foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
                {
                    //这里只对绑定列的属性进行赋值
                    if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
                    {
                        if (update.ContainsKey(ProInfo.Name))
                        {
                            values += ProInfo.Name + "=" + checkField(update[ProInfo.Name].ToString().Trim(), ProInfo.PropertyType.ToString()) + ",";
                        }
                        if (updateId.ContainsKey(ProInfo.Name))
                        {
                            Dictionary<string, int> updateWhereValue = updateId[ProInfo.Name];


                            if (updateWhereValue.First().Value == 0)
                            {
                                if (updateWhereValue.First().Key.ToLower() == "null")
                                    _where += ProInfo.Name + " is null and ";
                                else
                                    _where += ProInfo.Name + "=" + checkField(updateWhereValue.First().Key, ProInfo.PropertyType.ToString()) + " and ";
                            }
                            //else if (updateWhereValue.First().Value == 1)
                            //{
                            //    WhereString += ProInfo.Name + ">" + checkField(updateWhereValue.First().Key, ProInfo.PropertyType.ToString()) + " and ";
                            //}
                            else if (updateWhereValue.First().Value == -1)
                            {
                                if (updateWhereValue.First().Key.ToLower() == "null")
                                    _where += ProInfo.Name + " is  not null and ";
                                else
                                    _where += ProInfo.Name + "<>" + checkField(updateWhereValue.First().Key, ProInfo.PropertyType.ToString()) + " and ";
                            }
                            else if (updateWhereValue.First().Value == 1)
                            {
                                _where += "(";
                                foreach (var iq in updateWhereValue)
                                {

                                    if (iq.Key.ToLower() == "null")
                                    {
                                        _where += ProInfo.Name + " is  null";
                                    }
                                    else
                                    {
                                        _where += ProInfo.Name + "=" + checkField(iq.Key, ProInfo.PropertyType.ToString());
                                    }
                                    _where += " or ";
                                }
                                if (!string.IsNullOrEmpty(_where))
                                {
                                    _where = _where.Remove(_where.Length - 4);
                                }
                                _where += ") and ";
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(values))
                {
                    values = values.Remove(values.Length - 1);
                }
                if (!string.IsNullOrEmpty(_where))
                {
                    _where = _where.Remove(_where.Length - 5);
                }
                sqlvalue.Add(values + " where " + _where);
            }

            for (int i = 0; i < (sqlvalue.Count() / 1000 + ((sqlvalue.Count() % 1000) != 0 ? 1 : 0)); i++)
            {
                for (int j = 0; (i * 1000 + j) < sqlvalue.Count() && j < 1000; j++)
                {
                    sql += " update " + tableName + " set   " + sqlvalue[i * 1000 + j].ToString().Trim();
                }
            }
            //SQL命令
            //获取SQL参数数组 (包括查询参数和赋值参数)
            command.CommandText = sql;
            command.CommandTimeout = 1000 * 10;
            //执行 
            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    command.Connection.Open();
                }
                return command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
                command.Dispose();
            }
        }

        private static String GetTableFieldName(Type TableType, String PropertyName)
        {
            IEnumerable<PropertyInfo> ProInfos = TableType.GetProperties().Where(pro => pro.Name.ToLower() == PropertyName.ToLower());
            if (ProInfos.Count() == 0)
            {
                return "";
            }
            else
            {
                var ProInfo = ProInfos.First();
                var Column = ProInfo.GetCustomAttribute<ColumnAttribute>();
                var Table = TableType.GetCustomAttribute<TableAttribute>();

                if (Column == null)
                {
                    return "";
                }
                else
                {
                    return Table.Name + "." + (Column.Name.IsEmptyString() ? PropertyName : Column.Name);
                }
            }
        }

        private static ColumnAttribute GetTableColumn(Type TableType, String PropertyName)
        {
            IEnumerable<PropertyInfo> ProInfos = TableType.GetProperties().Where(pro => pro.Name.ToLower() == PropertyName.ToLower());
            if (ProInfos.Count() == 0)
            {
                return null;
            }
            else
            {
                var ProInfo = ProInfos.First();
                return ProInfo.GetCustomAttribute<ColumnAttribute>();
            }
        }

        public static int UpdateBatch<T>(Dictionary<string, string> UpdateFields, XWhereCollection UpdateWheres, DataContext dataContext) where T : class
        {
            //获取表名
            Type TableType = typeof(T);
            String ExecSql = string.Empty;
            StringBuilder UpdateSetStringBulider = new StringBuilder();
            String UpdateSetString = "";
            UpdateSetStringBulider.Append(" set ");
            String TableName = TableType.GetCustomAttribute<TableAttribute>().Name;
            foreach (var UpdateField in UpdateFields)
            {
                String ColumnName = GetTableFieldName(TableType, UpdateField.Key);
                ColumnAttribute Column = GetTableColumn(TableType, UpdateField.Key);
                if (ColumnName.IsEmptyString())
                {
                    throw new Exception("未在" + TableType.Name + " 中 找到 " + UpdateField.Key + " 属性对应的数据库字段映射");
                }
                else
                {
                    UpdateSetStringBulider.Append(ColumnName + " = " + GetDBValueString(Column.DbType, UpdateField.Value) + ",");
                }
            }

            UpdateSetString = UpdateSetStringBulider.ToString().Substring(0, UpdateSetStringBulider.Length - 1);
            ExecSql = " Update " + TableName + UpdateSetString + " Where " + UpdateWheres.ToSqlString(TableType);

            return dataContext.ExecuteCommand(ExecSql);
        }

        public static String GetDBValueString(String TableFieldType, List<String> FieldValues)
        {
            StringBuilder ReturnString = new StringBuilder();
            if (TableFieldType.ToLower().Contains("char"))
            {
                foreach (String FieldValue in FieldValues.Distinct())
                {
                    ReturnString.Append("'" + FieldValue + "',");
                }
            }
            else if (TableFieldType.ToLower().Contains("uniqueidentifier") || TableFieldType.ToLower().Contains("datetime"))
            {
                foreach (String FieldValue in FieldValues.Distinct().Where(value => value != ""))
                {
                    if (FieldValue.ToLower() != "null")
                    {
                        ReturnString.Append("'" + FieldValue + "',");
                    }
                    else
                    {
                        ReturnString.Append(" " + FieldValue + " ,");
                    }
                }
            }
            else
            {
                foreach (String FieldValue in FieldValues)
                {
                    ReturnString.Append(FieldValue + ",");
                }
            }

            return "(" + ReturnString.ToString().Substring(0, ReturnString.Length - 1) + ")";
        }

        public static String GetDBValueString(String TableFieldType, String FieldValue)
        {
            StringBuilder ReturnString = new StringBuilder();
            if (TableFieldType.ToLower().Contains("char"))
            {
                ReturnString.Append("'" + FieldValue + "',");
            }
            else if (TableFieldType.ToLower().Contains("uniqueidentifier") || TableFieldType.ToLower().Contains("datetime"))
            {
                if (FieldValue.ToLower() != "null")
                {
                    ReturnString.Append("'" + FieldValue + "',");
                }
                else
                {
                    ReturnString.Append(" " + FieldValue + " ,");
                }
            }
            else
            {
                ReturnString.Append(FieldValue + ",");
            }

            return ReturnString.ToString().Substring(0, ReturnString.Length - 1);
        }



        public static string checkField(string filed, string PropertyType)
        {
            PropertyType = PropertyType.ToLower();
            if (PropertyType.Contains("system.string") || PropertyType.Contains("system.datetime") || PropertyType.Contains("system.guid"))
                return "'" + filed + "'";
            return filed;
        }


        //public static void Update<TTableName>(TTableName NewData, Func<TTableName, bool> UpdateFunc, DataContext dataContext) where TTableName : class
        //{
        //    TTableName OldData = dataContext.GetTable<TTableName>().Single(UpdateFunc);
        //    CopyValue<TTableName>(OldData, NewData, dataContext);
        //    dataContext.SubmitChanges();
        //}

        //private static void CopyValue<TTableName>(TTableName OldValue, TTableName NewValue, DataContext dataContext)
        //{
        //    Type tableType = typeof(TTableName);

        //    foreach (System.Reflection.PropertyInfo ProInfo in tableType.GetProperties())
        //    {
        //        //这里只对绑定列的属性进行赋值
        //        if (ProInfo.GetCustomAttributes(true).Where(pre => pre.ToString() == typeof(ColumnAttribute).ToString()).Count() > 0)
        //        {
        //            ProInfo.SetValue(OldValue, ProInfo.GetValue(NewValue, null), null);
        //        }

        //        //级联更新外键表
        //        //判断属性是否是另一个表的外键(是否和另一个表为一对多的关系)
        //        Boolean IsPrimaryKey = false;
        //        foreach (var KeyMember in ProInfo.GetCustomAttributes(typeof(AssociationAttribute), false))
        //        {
        //            IsPrimaryKey = !((AssociationAttribute)KeyMember).IsForeignKey;
        //        }

        //        if (IsPrimaryKey)
        //        {
        //            //要更新的相关记录
        //            var ForeignValues = ProInfo.GetValue(NewValue, null);
        //            //Type ForeignType = ProInfo.GetValue(NewValue, null).GetType();//类型为:EntitySet<TableType>
        //            //Type ForeignTableType = ProInfo.GetValue(NewValue, null).GetType().GetGenericArguments()[0];
        //            Type ForeignType = ProInfo.PropertyType;//类型为:EntitySet<TableType>
        //            if (ForeignType.IsGenericType)//判断是否为泛型
        //            {
        //                Type ForeignTableType = ProInfo.GetValue(NewValue, null).GetType().GetGenericArguments()[0]; var ProHasLoadedOrAssignedValues = ForeignType.GetProperty("HasLoadedOrAssignedValues");
        //                if (ForeignTableType.GetProperty("ISLINKTABLE") != null)
        //                {
        //                    //如果需要更新的类中该属性为空则不对相关的记录作更新
        //                    if (ProHasLoadedOrAssignedValues != null)
        //                    {
        //                        Boolean HasLoadedOrAssignedValues = (Boolean)ProHasLoadedOrAssignedValues.GetValue(ForeignValues, null);
        //                        if (HasLoadedOrAssignedValues)
        //                        {
        //                            /*
        //                             * 注意:
        //                             * 这里的删除子表只使用于关联表的关系删除,子表为非关联表或者还有下级子表时不做删除,让其自然报错
        //                             */
        //                            //删除子表中所有的相关内容
        //                            foreach (var ChildTable in ProInfo.GetValue(OldValue, null) as IEnumerable<object>)
        //                            {
        //                                Type ForeignValueType = ForeignType.GetGenericArguments()[0];
        //                                ITable IChildTable = dataContext.GetTable(ForeignValueType);
        //                                IChildTable.DeleteOnSubmit(ChildTable);
        //                            }
        //                            //向子表中插入新的数据
        //                            ProInfo.SetValue(OldValue, ProInfo.GetValue(NewValue, null), null);
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}
        //public static void Insert<TTableName>(TTableName gb, DataContext dataContext) where TTableName : class
        //{
        //    dataContext.GetTable<TTableName>().InsertOnSubmit(gb);
        //    dataContext.SubmitChanges();
        //}
        //public static void InsertLists<TTableName>(List<TTableName> db, DataContext dataContext) where TTableName : class
        //{
        //    dataContext.GetTable<TTableName>().InsertAllOnSubmit(db);
        //    dataContext.SubmitChanges();
        //}

        //public static void Delete<TTableName>(Func<TTableName, bool> DelectBDS, DataContext dataContext) where TTableName : class
        //{
        //    var deleteValues = dataContext.GetTable<TTableName>().Where(DelectBDS);
        //    dataContext.GetTable<TTableName>().DeleteAllOnSubmit(deleteValues);
        //    dataContext.SubmitChanges();
        //}

    }
}


本文来自 小周的技术博客 转载请注明;

本文地址:http://blog.lyttensoft.win/?id=59

发表评论:

小周的技术博客