itsalikis
itsalikis

Reputation: 11

Get List<string> or Dictionary using Dapper

SQLite query is

SELECT * FROM tblProducts WHERE Id = 1

How to get List<string> of all values or Dictionary with property and value, with Dapper;

Upvotes: -2

Views: 59

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063844

var row = (IDictionary<string,object>)connection.QuerySingle(
    "SELECT * FROM tblProducts WHERE Id = 1");

The non-generic query API returns dynamic objects, but those objects also support dictionary access. However, this is the least efficient way to use Dapper. If you know the shape of your data - and you should - then QuerySingle<YourTypeHere>(...) is preferable.

Upvotes: 1

Shoeb Hasan
Shoeb Hasan

Reputation: 36

Here is a code snippet you can try with, you may need to change your query. It would be better if you specify the column names instead of *. The following example is valid for dictionary.

public List<Dictionary<string, object>> GetProductValues()
{
    const string connectionString = "Data Source=put_your_database_info";
    const string query = "SELECT * FROM tblProducts WHERE Id = 1";

    using (var connection = new SQLiteConnection(connectionString))
    {
        connection.Open();
        var result = connection.Query(query);
        var list = result.Select(row => (IDictionary<string, object>)row).ToList();
        var dictionaryList = list.Select(dict =>
            dict.ToDictionary(kvp => kvp.Key, kvvp => kvvp.Value)).ToList();
        return dictionaryList;
    }
}

Upvotes: -2

Related Questions