1. 程式人生 > >EF 返回DataTable 擴展方法

EF 返回DataTable 擴展方法

extend ndt odata ret string database catch exce urn

    public static class EFExtendMethod
    {
        public static DataTable SqlQueryToDataTable(this Database db, string sql, CommandType type = CommandType.Text, params SqlParameter[] param)
        {
            DataTable ret_dt = new DataTable();
            SqlConnection conn = db.Connection as SqlConnection;
            if (conn == null)
            {
                conn = new SqlConnection(db.Connection.ConnectionString);
            }

            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            try
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.CommandType = type;

                if (param != null && param.Length > 0)
                {
                    foreach (SqlParameter p in param)
                    {
                        cmd.Parameters.Add(p);
                    }
                }

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(ret_dt);

                conn.Close();
                return ret_dt;
            }
            catch (Exception ex)
            {
                conn.Close();
                return ret_dt;
            }
        }

        public static DataTable SqlQueryToDataTable(this Database db, string sql, params SqlParameter[] param)
        {
            return SqlQueryToDataTable(db,sql,CommandType.Text,param);
        }
    }

  

EF 返回DataTable 擴展方法