编辑:
List<Organization> orgs = helperDb.QueryAllOnTable("Organization");
型号:
public class Organization
{
public string Id { get; set; }
public string Type { get; set; }
}
我正在研究查询任何表的泛型类,只需传递模态名称表名,但我被困在这里......任何帮助?
最佳重载方法匹配 &#39; System.Collections.Generic.List.Add(T)&#39;有一些无效的论点
public List<T> QueryAllOnTable<T>(string table)
{
try
{
this.OpenConn();
List<T> lstSelect = new List<T>();
string SQL = "SELECT * FROM " + table + ";";
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
lstSelect.Add(dr[i]); //<<< throwing ERROR
}
}
this.CloseConn();
return lstSelect;
}
catch (Exception ne)
{
Console.WriteLine("error on query table connecting to server, Error details {0}", ne.ToString());
return null;
}
}
答案 0 :(得分:3)
dr[i]
是object
,您需要明确地将其投放到T
:
lstSelect.Add((T)dr[i])
当然,如果特定数据单元格中的值不是类型的T,那么您将获得运行时异常。