Search code examples
c#linqdapperdapper-extensions

How to Deal With Dapper return Key Value pair with Dynamic from LINQ


I am new to Dapper. Let me explain what i am trying to achieve. I have simple query which is returning columns from DB, i don't want to create Entity(Property) class for it to fill the data. I want to use Dynamic Type for this. Below is my code:

public dynamic GetABC(int year)
    {

        using (var db = new MySql.Data.MySqlClient.MySqlConnection(ClsConnectionString.connectionString))
        {

            string query = string.Format(@"SELECT * FROM ranking where YEAR(eventdate)='{0}') ORDER BY eventdate DESC, eventid ASC",year);
            //return db.Query<RankingEntity>(query, commandType: System.Data.CommandType.Text).AsList();
            var a = (IEnumerable<dynamic>)db.Query(query, null, null, true, null, CommandType.Text).ToList();
            return a;
       }
    }

It returns me Key Value pair. like below: Dapper Row

Is there any way, i just write one common method to get List as "Property" = "Value" As normally we get when we use any Entity Class.

I am not sure, if it is achievable but i wish to learn if it is possible and want to implement in our application.

I can achieve this by implementing loop through the dapperrows which i don't want. because if there will be 10000 rows loop will iterate 10000 times.

Thanks in advance.


Solution

  • As I have mentioned DapperRow is an internal class of the Dapper, which can be directly typecast to IDictionary<string,object>, since it implements IDictionary interface. All that you have to do is:

    var a = db.Query(query, null, null, true, null, CommandType.Text).Select(x => x as IDictionary<string,object>);
    

    Now result would be of type IEnumerable<IDictionary<string,object>>, which can be used to extract all the required information, since column names are keys and respective row value is the value of each element in the IEnumerable.

    Also check, this may too work, but I am not sure:

     var a = (IEnumerable<IDictionary<string,object>>)db.Query(query, null, null, true, null, CommandType.Text);