如何使用Dapper动态获取列的值

时间:2014-02-28 21:15:36

标签: dapper

使用Dapper,如何动态获取表中列的值?

我有什么:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以将实体转换为IDictionary<string, object>并按名称访问:

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