How to Work with Returning Dapper Key Value Pair with Dynamic from LINQ

I am new to Dapper. Let me explain what I am trying to achieve. I have a simple query that returns columns from DB, I don't want to create an Entity (Property) class to populate 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 a couple of key values. as shown below: Dapper row

Is there a way, I just write one generic method to get the List as "Property" = "Value" As we usually get when we use any Entity Class.

I'm not sure if this is achievable, but I want to know if it is possible and what needs to be implemented in our application.

I can achieve this by implementing a loop through dapperrows, which I don't want. because if there are 10,000 lines, the loop will repeat 10,000 times.

Thanks in advance.

+3


source to share


1 answer


As I said, it DapperRow

is an inner class Dapper that can be directly typecast on IDictionary<string,object>

since it implements the interface IDictionary

. All you have to do is:

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

      

The result will now be of a type IEnumerable<IDictionary<string,object>>

that can be used to retrieve all the information needed, since the column names are keys and the corresponding row value is the value of each item in IEnumerable

.



Also check, this might work too, but I'm not sure:

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

      

+4


source







All Articles