Пример #1
0
        /// <summary>
        /// 插入一条新的记录
        /// </summary>
        /// <typeparam name="T">实体泛型</typeparam>
        /// <param name="idb">数据库连接上下文</param>
        /// <param name="entity">待新增的实体,注意:如果是Sql server标识列或者oracle使用序列生成主键的,主键请留空。</param>
        /// <returns>返回影响的记录条数</returns>
        public static int Insert <T>(this IDbHelper idb, T entity) where T : class, new()
        {
            string sql;
            IList <IDataParameter> paras = null;

            // 获取插入的参数列表
            paras = DALUtil.GetModelInsertParas <T>(entity, out sql, idb);

            if (idb.DBType == DataBaseType.SqlServer && DALUtil.IsIdentityTable <T>())
            {
                return(Convert.ToInt32(idb.ExecuteScalar(CommandType.Text, sql, paras.ToArray())));
            }
            else if (idb.DBType == DataBaseType.Oracle && DALUtil.SequenceInsert <T>())
            {
                string seqname = DALUtil.GetSequenceName <T>();
                // 如果启用事务
                if (idb.IsStartTrans)
                {
                    idb.ExecuteNonQuery(CommandType.Text, sql, paras.ToArray());

                    int n = Convert.ToInt32(idb.ExecuteScalar(string.Format("SELECT {0}.CURRVAL FROM DUAL", seqname)));
                    return(n);
                }
                // 不启动事务
                else
                {
                    try
                    {
                        idb.BeginTrans();
                        idb.ExecuteNonQuery(CommandType.Text, sql, paras.ToArray());

                        int n = Convert.ToInt32(idb.ExecuteScalar(string.Format("SELECT {0}.CURRVAL FROM DUAL", seqname)));
                        idb.CommitTrans();
                        return(n);
                    }
                    catch (Exception ex)
                    {
                        idb.RollTrans();

                        throw ex;
                    }
                }
            }
            else
            {
                return(idb.ExecuteNonQuery(CommandType.Text, sql, paras.ToArray()));
            }
        }