예제 #1
0
 private static async Task EnsureClosedAsync(this DbDataReader reader)
 {
     if (reader == null)
     {
         return;
     }
     if (reader.IsClosed)
     {
         return;
     }
     await reader.CloseAsync();
 }
예제 #2
0
        /// <summary>
        /// Getting result extensions methods for <see cref="DbDataReader"/> that will map the result
        /// to the list of type <typeparamref name="TDestination"/>.
        /// </summary>
        /// <typeparam name="TDestination">Must have a public parameterless constructor.</typeparam>
        /// <returns>A list of type <typeparamref name="TDestination"/>.</returns>
        /// <exception cref="ArgumentNullException">The specific argument is null.</exception>
        /// <exception cref="ResultOutOfRangeException">Requested result of the DataReader is outside the
        /// allowable range of results.</exception>
        public static async Task <List <TDestination> > GetResultAsync <TDestination>(this DbDataReader reader) where TDestination : new()
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader is null.");
            }

            if (reader.IsClosed)
            {
                throw new ResultOutOfRangeException();
            }

            var entityType = typeof(TDestination);
            List <TDestination> entities = null;
            var propertyDictionary       = new Dictionary <string, PropertyInfo>();

            if (reader != null && reader.HasRows)
            {
                entities = new List <TDestination>();

                var entityProperties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                propertyDictionary = entityProperties.ToDictionary(p => p.Name.ToUpper(), p => p);

                while (await reader.ReadAsync().ConfigureAwait(false))
                {
                    var entity = new TDestination();

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        var fieldName = reader.GetName(i).ToUpper();
                        if (propertyDictionary.ContainsKey(fieldName))
                        {
                            var propertyInfo = propertyDictionary[fieldName];
                            if (propertyInfo != null && propertyInfo.CanWrite)
                            {
                                var fieldValue = reader.GetValue(i);
                                propertyInfo.SetValue(entity, (fieldValue == DBNull.Value) ? null : fieldValue, null);
                            }
                        }
                    }

                    entities.Add(entity);
                }
            }

            if (await reader.NextResultAsync().ConfigureAwait(false) == false)
            {
                await reader.CloseAsync().ConfigureAwait(false);
            }

            return(entities);
        }
예제 #3
0
        /// <summary>
        /// 执行SQL查询
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">参数集</param>
        /// <returns>实体对象集合</returns>
        public async Task <ICollection <TEntity> > ExecuteSqlQueryAsync <TEntity>(string sql, params object[] parameters)
        {
            #region # 验证

            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException(nameof(sql), "SQL语句不可为空!");
            }

            #endregion

            DbConnection dbConnection = this._dbContext.Database.GetDbConnection();
            if (dbConnection.State != ConnectionState.Open)
            {
                await dbConnection.OpenAsync();
            }
            DbCommand dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = sql;
            if (parameters != null && parameters.Any())
            {
                dbCommand.Parameters.AddRange(parameters);
            }

            DbDataReader dataReader = await dbCommand.ExecuteReaderAsync();

            DataTable dataTable = new DataTable();
            dataTable.Load(dataReader);
#if NETSTANDARD2_0
            dataReader.Close();
#endif
#if NETSTANDARD2_1
            await dataReader.CloseAsync();
#endif
            //获取类型与属性列表
            Type           type          = typeof(TEntity);
            PropertyInfo[] propertyInfos = type.GetProperties();

            //获取无参构造函数
            ConstructorInfo[] constructors       = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            ConstructorInfo   noParamConstructor = constructors.Single(ctor => ctor.GetParameters().Length == 0);

            IList <TEntity> entities = new List <TEntity>();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                TEntity entity = (TEntity)noParamConstructor.Invoke(null);
                foreach (PropertyInfo property in propertyInfos)
                {
                    if (dataTable.Columns.Contains(property.Name))
                    {
                        MethodInfo propertySetter = property.GetSetMethod(true);
                        if (propertySetter != null)
                        {
                            object value = dataRow[property.Name] == DBNull.Value
                                ? null
                                : dataRow[property.Name];
                            propertySetter.Invoke(entity, new[] { value });
                        }
                    }
                }
                entities.Add(entity);
            }

            return(entities);
        }
 /// <summary>
 /// Closes the asynchronous.
 /// </summary>
 public async Task CloseAsync()
 {
     await _reader.CloseAsync().ConfigureAwait(false);
 }