Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I return a list of objects corresponding to records in my database?
    text
    copied!<p>I am new to C# and I am struggling with everything, please help. Here is what I am trying to do:</p> <p>Create a database Class which returns a dynamic list which contains instances of a class depending on the table being queried:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.IO; using System.Reflection; Class MYDatabase{ public void main () { String QueryString="select COLUMN_NAME, DATA_TYPE from information_schema.columns where table_name = 'mytable'"; Object MyData=GetRsults(QueryString,"SchemaStructure"); } public static Object GetResults(string QueryString, String ClassName) { SqlCommand cmd = new SqlCommand(); SqlDataReader reader; cmd.CommandText = QueryString; cmd.CommandType = CommandType.Text; //assuming I already defined my connection cmd.Connection = Connection; Connection.Open(); reader = cmd.ExecuteReader(); Type ClassType = Type.GetType(ClassName); Type ListType = typeof(List&lt;&gt;).MakeGenericType(new Type[] { ClassType }); Object Results = Activator.CreateInstance(ListType); Object SingleResult = Activator.CreateInstance(ClassType); while (reader.Read()) { for (int i = 0; i &lt; reader.FieldCount; i++) { var PropName= SingleResult.GetType().GetProperty(reader.GetName(i).ToString()); //Convert.ChangeType(value, propertyInfo.PropertyType) PropName.SetValue(PropName,reader.GetValue(i).ToString(),null); } Results.Add(SingleResult); } Connection.Close(); return Results; } } class SchemaStructure { public string COLUMN_NAME { set; get; } public string DATA_TYPE { set; get; } } </code></pre> <p>This is not working, the line <code>Results.Add(SingleResult);</code> gives me a message</p> <p>'object' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) </p> <p>Can anyone please help me resolve this code?</p> <p>I am open to other suggestions if my approach doesn't make sense at all.</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload