添加新增 删除旧的 避免id自增过多

    /// <summary>
        
///  编辑关联分类 的属性 添加新值删除去掉的值
        
/// </summary>
        
/// <param name="IListNew">最新的分类信息</param>
        
/// <returns>是否更新成功</returns>
        public bool Update(IList<CategoryAttributeInfo> IListNew, int categoryID)
        {
            IList
<CategoryAttributeInfo> IListOld = new List<CategoryAttributeInfo>();//取出数据库里的分类
            IList<CategoryAttributeInfo> IListDel = new List<CategoryAttributeInfo>();//待删除的
            IList<CategoryAttributeInfo> IListAdd = new List<CategoryAttributeInfo>();//待添加的

            IListOld 
= GetCategoryAttributeInfoList("CategoryID=" + categoryID, "");


            
//对比取出 那些该删除 那些该添加
            foreach (CategoryAttributeInfo iListOld in IListOld)
            {
                
if (IListNew.Contains(iListOld))
                {
                    IListNew.Remove(iListOld);
                }
                
else
                {
                    IListDel.Add(iListOld);
                }

            }
            IListAdd 
= IListNew;

            
using (SqlTransaction sqlTran = SqlHelper.BeginTransaction())
            {
                
try
                {
                    
foreach (CategoryAttributeInfo CategoryAttributeInfo in IListDel)
                    {
                        SqlHelper.ExecuteNonQuery(sqlTran, 
"delete  from t_CategoryAttribute where ID=" + CategoryAttributeInfo.ID, null);
                    }

                    
//添加新增的 分类属性
                    foreach (CategoryAttributeInfo CategoryAttributeInfo in IListAdd)
                    {
                        Add(CategoryAttributeInfo);
                    }

                    sqlTran.Commit();
                    
return true;

                }
                
catch
                {
                    sqlTran.Rollback();
                    
return false;
                }
            }

        }
原文地址:https://www.cnblogs.com/aaa6818162/p/1519836.html