Convert rows from a data reader into typed results

后端 未结 10 2256
醉梦人生
醉梦人生 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:22

    Whilst I wouldn't recommend this for production code, but you can do this automatically using reflection and generics:

    public static class DataRecordHelper
    {
        public static void CreateRecord(IDataRecord record, T myClass)
        {
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
    
            for (int i = 0; i < record.FieldCount; i++)
            {
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (propertyInfo.Name == record.GetName(i))
                    {
                        propertyInfo.SetValue(myClass, Convert.ChangeType(record.GetValue(i), record.GetFieldType(i)), null);
                        break;
                    }
                }
            }
        }
    }
    
    public class Employee
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public DateTime? BirthDate { get; set; }
    
        public static IDataReader GetEmployeesReader()
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
    
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT EmployeeID As Id, LastName, BirthDate FROM Employees"))
            {
                cmd.Connection = conn;
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
    
        public static IEnumerable GetEmployees()
        {
            IDataReader rdr = GetEmployeesReader();
            while (rdr.Read())
            {
                Employee emp = new Employee();
                DataRecordHelper.CreateRecord(rdr, emp);
    
                yield return emp;
            }
        }
    }
    

    You can then use CreateRecord() to instantiate any class from the fields in a data reader.

    
    
    GvEmps.DataSource = Employee.GetEmployees();
    GvEmps.DataBind();
    

提交回复
热议问题