How to get value of column dynamically using Dapper

dapper

Question

Using Dapper, how can I get the value of a column within a table dynamically?

What I have:

string tableName = "Table1";
int itemId = 1;
string columName = "MyBitColumn";

var query = string.Format("select {0} from {1} where {1}Id = @itemId", columnName, tableName);
var entity = conn.Query(query, new { itemId }).FirstOrDefault();

// I'd like something like this...
bool val = entity[columnName] as bool; // returns true or false, given that "MyBitColumn" is a bit in my sql db

Thanks!

Accepted Answer

You can cast the entity to an IDictionary<string, object> and access by name:

var entity = (IDictionary<string, object>) ... // your code
if((bool)entity[column name]) { ... }


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