Search code examples
c#oracle-databaselinqlambdaresultset

Map query result to typed list


Here is how I get the result(example):

OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from table_name t";     
//retrieve the result
OracleDataReader reader =  cmd.ExecuteReader();

Then I have a POCO class that matches the fields of the query(row by row). That being said, I create a List:

List<ReportsModel> reports= new List<ReportsModel>();

Then I iterate over the reader:

while (reader.Read())
{
      //single report that I will pass to the colletion of reports
      ReportsModel report= new ReportsModel();
      report.Id_product = reader["ID_PRODUCT"] == DBNull.Value ? 0 : Convert.ToInt32(reader["ID_PRODUCT"]); 


      //passing report to reports
      reports.Add(report );
}

The problem is: my POCO class has around 300 fields(the query returns the same amount also). How can I map my result set (OracleDataReader reader) to my List<ReportsModel> without having to fetch row by row (report.Id_product = reader["ID_PRODUCT"])? I know that there may be a way to solve it using something like lambda(arrow function) along with Linq or whatever.


Solution

  • I took the @mjwills suggestion on using Dapper and it solved my issue, here is my code:

    string sql = "select * from table t ";   
    
    //conn changed to IDbConnection, so I could use Dapper
    var reports= conn.Query<ReportsModel>(sql).ToList();
    

    And that's it, no need to write the code to iterate over OracleDataReader or anything else! Dapper handled it amazingly \o

    Useful: Dapper Example