如何在 Mono Data 中获取 DataTable SQL

How to get DataTable in Mono Data SQL

我编写了一个函数来获取数据库中的对象列表

public List<T> GetList<T>() where T: new()
{
    IDbCommand dbCmd = dbcon.CreateCommand();
    dbCmd.CommandText = "SELECT * FROM " + typeof(T).FullName;
    IDataReader reader = dbCmd.ExecuteReader();
    DataTable schemaTable = reader.GetSchemaTable();

    List<T> returnList = new List<T>();
    foreach (DataRow row in schemaTable.Rows)
    {
        T obj = new T();
        foreach(var prop in obj.GetType().GetProperties())
        {
            prop.SetValue(obj, row[prop.Name], null);
        }
        returnList.Add(obj);
    }

    return returnList;
}

但是例如,如果我 运行 我的武器 class 这有

public int ID { get; set;}
public int Cost { get; set; }
public int Power { get; set; }
public int Distance { get; set; }

我得到 25 列,如果 运行 为 Monster class 我得到相同的 25 列 "ColumnName"、"ColumnOrdinal"、"ColumnSize", "NumericPrecision" 等...

因此我无法设置 "Cost" 属性,因为此数据集没有成本列名称。

如何正确获取SchemaTable?

我在没有使用 SchemaTable 的情况下解决了我的问题

public List<T> GetList<T>() where T: new()
{
    IDbCommand dbCmd = dbcon.CreateCommand();
    dbCmd.CommandText = String.Format("SELECT * FROM {0}", typeof(T).FullName);
    IDataReader reader = dbCmd.ExecuteReader();

    List<T> returnList = new List<T>();
    while (reader.Read())
    {
        T obj = new T();
        foreach(var prop in obj.GetType().GetProperties())
        {
            prop.SetValue(obj, Convert.ChangeType(reader[prop.Name], prop.PropertyType), null);
        }
        returnList.Add(obj);
    }

    return returnList;
}

此脚本成功获取给定 table 中的所有项目。