return 原始 sql 作为字典

return raw sql as dictionary

大家好我正在尝试编写代码来获取 select table 带有(字符串)table 名称的信息,但是当我尝试将值赋给字典。 P.S : 我已经生成了 EF DB 模型。

public Dictionary<string, List<object>> GetTableInformation(string tableName, FinkonaDatabaseType type)
    {
        Dictionary<string, List<object>> _returnableDictionary = new Dictionary<string, List<object>>();
        PropertyInfo prop = optimumEntities.GetType().GetProperty(tableName);
        Type tableType = prop.PropertyType.GenericTypeArguments[0];
        var items = optimumEntities.Database.SqlQuery(tableType, "SELECT * FROM " + tableName);

        foreach (var item in items)
        {
            foreach (PropertyInfo info in item.GetType().GetProperties())
            {
                if (!_returnableDictionary.ContainsKey(info.Name))
                {
                    _returnableDictionary.Add(info.Name, new List<object>());
                }
                _returnableDictionary[info.Name].Add(info.GetValue(info, null)); 
                // System.Reflection.TargetException, Object does not match target type.
            }
        }
        return _returnableDictionary;
    }

这里使用 ADO.NET DataTables 会更容易,因为 EF 用于强类型数据。由于您不太担心返回的数据类型,DataTable 将更易于导航。

这是一个例子:

public Dictionary<string, List<object>> GetTableInformation(string tableName, FinkonaDatabaseType type)
{
   var sqlText = "SELECT * from " + tableName;
   DataTable dt = new DataTable();

   // Use DataTables to extract the whole table in one hit
   using(SqlDataAdapter da = new SqlDataAdapter(sqlText, optimumEntities.Database.ConnectionString)
   {
      da.Fill(dt);   
   }

   var tableData = new Dictionary<string, List<object>>();

   // Go through all columns, retrieving their names and populating the rows
   foreach(DataColumn dc in dt.Columns)
   {
      string columnName = dc.Name;
      rowData = new List<object>();
      tableData.Add(columnName, rowData);

      foreach(DataRow dr in dt.Rows)
      {
         rowData.Add(dr[columnName]);   
      }
   }

   return tableData;
}