SqlQueryToList 执行SQL语句并把结果返回成一个List

时间:2021-06-18 15:56:32

返回一个动态结果集. 编程的时候用起来方便一些.

 /// <summary>
        /// EF SQL 语句返回 List<dynamic>
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql"></param>
        /// <param name="paras"></param>
        /// <returns></returns>
        public static List<dynamic> SqlQueryToList(this System.Data.Entity.DbContext db, string sql,  params IDataParameter[] paras)
        {

            //SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            //conn.ConnectionString = db.Connection.ConnectionString;
            //if (conn.State != ConnectionState.Open)
            //{
            // conn.Open();
            //}

            SqlConnection conn = GetSqlConnect(db.Database.Connection);

            //conn = (SqlConnection)db.Connection;
            SqlCommand cmd = new SqlCommand();
            if (paras != null)
            {
                cmd.Parameters.AddRange(paras);
            }
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);

            List<dynamic> os = new List<dynamic> ();
            foreach (DataRow row in table.Rows)
            {
                dynamic dobj  = new System.Dynamic.ExpandoObject();
                var dic = (IDictionary<string, dynamic>)dobj; //定义另外一个别名变量. 然后进行动态赋值..
                foreach (DataColumn col in table.Columns)
                {
                  dic[col.ColumnName] = row[col];// 上面不定义别名这里就不能用dic[]
                }
                os.Add(dobj);
            }
            //conn.Close();//连接需要关闭
            //conn.Dispose();
            return os;
        }