Convert rows from a data reader into typed results

后端 未结 10 2235
醉梦人生
醉梦人生 2020-11-27 11:53

I\'m using a third party library which returns a data reader. I would like a simple way and as generic as possible to convert it into a List of objects.
For example, say

10条回答
  •  渐次进展
    2020-11-27 12:39

    I found this solution.

    var cmd = ctx.Connection.CreateCommand();
    
    T result = DbDataReaderdHelper.Fill(cmd)
    
    public static class DbDataReaderdHelper
    {
        public static List Fill(DbCommand dbCommand) where T : new()
        {
            List result = new List();
            var reader = dbCommand.ExecuteReader();
    
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Type type = typeof(T);
                    T obj = (T)Activator.CreateInstance(type);
                    PropertyInfo[] properties = type.GetProperties();
    
                    foreach (PropertyInfo property in properties)
                    {
                        var value = reader[property.Name];
    
                        try
                        {
                            if (value != null)
                            {
                                var convertedValue = TypeDescriptor.GetConverter(property.PropertyType).ConvertFromInvariantString(value.ToString());
    
                                property.SetValue(obj, convertedValue);
                            }
                        }
                        catch {}
                    }
                    result.Add(obj);
                }
            }
    
            reader.Close();
    
            return result;
        }
    }
    

提交回复
热议问题