コード例 #1
0
        /// <summary>
        /// 根据主键获取实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="idb">数据库连接上下文</param>
        /// <param name="pk">主键 例如id=1 写入 GetEntityById(1)</param>
        /// <returns>如果存在该实体,返回实体,否则返回null。</returns>
        /// <remarks>
        /// 对于多主键实体,主键的顺序必须是 实体的顺序否则系统会取不到正确的数据。
        ///
        /// </remarks>
        public static T GetEntityById <T>(this IDbHelper idb, params object[] pk) where T : class, new()
        {
            // 根据实体获取主键
            var pklist = DALUtil.GetPKAttribute <T>();

            if (pklist.Count != pk.Count())
            {
                // 实体的主键 个数如果不一致 系统自动抛出异常
                throw new Exception("主键设置个数不一致");
            }
            List <IDataParameter> list = new List <IDataParameter>();

            string where = "1=1";
            for (int i = 0; i < pklist.Count; i++)
            {
                where += " AND " + pklist[i] + " = " + DALUtil.GetParameterPrefix(idb) + i.ToString();
                var idp = idb.GetIDataParameter();
                idp.ParameterName = DALUtil.GetParameterPrefix(idb) + i.ToString();
                idp.Value         = pk[i];
                list.Add(idp);
            }

            var dt = idb.ExecuteTable(CommandType.Text, string.Format("SELECT * FROM {0} WHERE {1}", DALUtil.GetTableName <T>(), where), list.ToArray());

            if (dt.Rows.Count > 0)
            {
                return(DALUtil.GetEntity <T>(dt)[0]);
            }
            else
            {
                return(default(T));
            }
        }
コード例 #2
0
        /// <summary>
        /// 根据指定主键删除一个实体
        /// </summary>
        /// <typeparam name="T">实体泛型</typeparam>
        /// <param name="idb">数据库连接上下文</param>
        /// <param name="pk">主键列表,注意:主键列表的顺序必须与实体完全一致</param>
        /// <returns>返回影响的记录条数,如果该数据不存在返回0</returns>
        public static int Delete <T>(this IDbHelper idb, object[] pk) where T : class, new()
        {
            string tablename = DALUtil.GetTableName <T>();
            var    pks       = DALUtil.GetPKAttribute <T>();

            if (pks.Count != pk.Length)
            {
                throw new Exception("主键个数与传入参数不一致");
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < pk.Length; i++)
            {
                sb.AppendFormat(" AND {0} = '{1}'", pks[i], pk[i]);
            }

            string sql = string.Format("DELETE FROM {0} WHERE 1=1{1}", tablename, sb.ToString());

            return(idb.ExecuteNonQuery(sql));
        }