How can I map the results of a sql query onto objects?

后端 未结 7 1657
灰色年华
灰色年华 2021-02-01 20:37

Currently, I am using something like this:

    try
    {
      dr = SQL.Execute(sql);

      if(dr != null) {
         while(dr.Read()) {
           CustomObject         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 21:05

    You can achieve by creating a generic method for your requirement. Also you can make your new method as the extension for the data table.

        public static List ToList(this DataTable table) where T : class, new()
    {
        try
        {
            List list = new List();
    
            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();
    
                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }
    
                list.Add(obj);
            }
    
            return list;
        }
        catch
        {
            return null;
        }
    }
    

    }

    Usage:

        DataTable dtCustomer = GetCustomers();
        List CustomObjectList = dtCustomer.ToList();
    

提交回复
热议问题