0

So I came across this code:

dynamic account = conn.Query<dynamic>(@"
                SELECT Name, Address, Country
                FROM Account
        WHERE Id = @Id", new { Id = Id }).FirstOrDefault();
Console.WriteLine(account.Name);
Console.WriteLine(account.Address);
Console.WriteLine(account.Country);

(How to return dynamic types List<dynamic> with Dapper ORM).

I was wondering how I could do the same using strings as parameters. Kinda like so:

dynamic account = conn.Query<dynamic>($@"
                SELECT {commaseperated(parameters)}
                FROM Account
        WHERE Id = @Id", new { Id = Id }).FirstOrDefault();
Console.WriteLine(account[parameters[0]]);
Console.WriteLine(account[parameters[1]]);

Where parameters is of type string[]. All results are of type string, so using dynamic may not even be necessary.

  • `so using dynamic may not even be necessary` bingo! There's no need to pull in dynamic types for this simple use case. – asawyer Jun 18 '20 at 13:08
  • So how do I loop through the results using the string parameters? If I loop through the query results I only get the first parameter, like so: var res = connection.Query(@$"SELECT {parameters.addCommas()} FROM..."); foreach(string s in res) { //s is just the first column/parameter } – GottaLovePizzas Jun 18 '20 at 16:35
  • Try `connection.Query>(...)` – asawyer Jun 18 '20 at 17:25

1 Answers1

0

I assume you could do something like this:

        string[] parameters = new string[] { "param1", "param2" };

        dynamic account = conn.Query<dynamic>($@"SELECT {String.Join(",", parameters)} FROM Account WHERE Id = @Id", new { Id }).FirstOrDefault();

        foreach (string s in parameters)
        {
            Console.WriteLine(account.GetType().GetProperty(s).GetValue(account, null));
        }

        Console.ReadLine();
NicoRiff
  • 4,803
  • 3
  • 25
  • 54