Dapper query result returns DapperRow collections: IEnumerable<dynamic>{List<Dapper.SqlMapper.DapperRow>}
. In order to use the data inside DapperRow object, we need to convert the data into usable types.
Table of Contents
Get single value
var data = conn.ExecuteScalar("select top 1 title from book"); string title = $"{data}";
int id = conn.ExecuteScalar<int>("select top 1 id from book");
Get data from a single row
var row = conn.QuerySingle("select top 1 title, url_target from book");
var title = $"{row.title}";
Get data as a Array:
var data = conn.Query("select title, url from book").Select(x => x.title).ToArray();
foreach(var d in data){
string title = d;
}
Get data as a List:
var data = conn.Query("select title, url from book").Select(x => x.title).ToList();
foreach(var d in data){
string title = d;
}
Get data as a Dictionary:
var data = conn.Query("select title, url from book").ToDictionary(row => (string)row.title, row => (string)row.url);
foreach(var k in data.Keys){
string key = k;
string value = data[k];
}
Get data as an object:
var books = conn.Query<Book>("select * from book"); //returns IEnumerable<Book>
foreach(var book in books){
string title = book.Title;
}
Dapper automatically mapped the column data to the fields in the object by their names.
Comments