Is there a way to access the columns in a Dapper FastExpando via string or index?

c# dapper dynamic

Question

I am pulling in a Dapper FastExpando object and want to be able to reference the column names dynamically at run time rather than at design/compile time. So I want to be able to do the following:

var testdata = conn.Query("select * from Ride Where RiderNum = 21457");

I want to be able to do the following:

foreach( var row in testdata) {
    var Value = row["PropertyA"];
}

I understand that I can do:

var Value = row.PropertyA;

but I can't do that since the name of the property i'm going to need won't be known until runtime.

The answer from this SO Question doesn't work. I still get the same Target Invocation exception. So...

Is there any way to do what I want to do with a Dapper FastExpando?

Accepted Answer

Sure, it is actually way easier than that:

var sql = "select 1 A, 'two' B";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row["A"].IsEqualTo(1);
row["B"].IsEqualTo("two");

Popular Answer

Regarding the portion of the title "or index?" - I needed to access results by index since the column names being returned changed sometimes, so you can use a variation of Sam Saffron's answer like this:

var sql = "select 1, 'two'";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row.Values.ElementAt(0).IsEqualTo(1);
row.Values.ElementAt(1).IsEqualTo("two");



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why