Esempio n. 1
0
        /// <summary>
        /// 根据唯一ID获取对象,返回实体,如果有多个则报错
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>返回实体类</returns>
        public async Task <T> GetModelByIdAsync <T, TId>(TId id) where T : IId <TId>, new()
        {
            if (CommOp.IsDefault(id))
            {
                return(default(T));
            }
            var    pid  = CreateParameter("ID", id);
            Type   type = typeof(T);
            string sql  = $"SELECT COUNT(1) FROM {AddFix(type.Name)} where ID=@ID";
            int    cnt  = CommOp.ToInt(await this.ExecGetObjectAsync(sql, pid));

            if (cnt == 0)
            {
                return(default(T));
            }
            if (cnt > 1)
            {
                throw new Exception("根据唯一的ID查到不止一条记录");
            }

            sql = $"SELECT * FROM {AddFix(type.Name)} where ID=@ID";
            List <IDataParameter> list = new List <IDataParameter>();
            DataTable             dt   = await this.ExecDataTableAsync(sql, pid);

            if (dt.Rows.Count == 1)
            {
                return(RowToModel <T>(dt.Rows[0]));
            }
            return(default(T));
        }