How can I map the results of a sql query onto objects?

后端 未结 7 1668
灰色年华
灰色年华 2021-02-01 20:37

Currently, I am using something like this:

    try
    {
      dr = SQL.Execute(sql);

      if(dr != null) {
         while(dr.Read()) {
           CustomObject         


        
7条回答
  •  佛祖请我去吃肉
    2021-02-01 21:14

    Assumption: if you need objects only for serialization or simple ad-hoc output.

    You can use ExpandoObject and SqlDataReader.GetSchemaTable() like this:

        private IEnumerable ReaderToAnonymmous(SqlCommand comm) {
            using (var reader = comm.ExecuteReader()) {
                var schemaTable = reader.GetSchemaTable();
    
                List colnames = new List();
                foreach (DataRow row in schemaTable.Rows) {
                    colnames.Add(row["ColumnName"].ToString());
                }
    
                while (reader.Read()) {
                    var data = new ExpandoObject() as IDictionary;
                    foreach (string colname in colnames) {
                        var val = reader[colname];
                        data.Add(colname, Convert.IsDBNull(val) ? null : val);
                    }
    
                    yield return (ExpandoObject)data;
                }
            }
        }
    

    Although there are posted faster solutions (i posted this as alternative lazy approach for ad-hoc SQL/Reader results/outputs).

提交回复
热议问题