1

I am using Dapper in the project, and it's ok if I need to get either the single primitive type (int, decimal, string, etc) or any db entity, but I need to read just 2 columns from the table, and I faced with lots of the challenges here:

This is a simple query:

SELECT col1, col2 FROM Table1

Where I expect to receive string and int

And this is how I read the data once the query is implemented:

var field1 =  (await result.ReadAsync<string, int>()).FirstOrDefault();

And this is not compilable. I tried to create the class which contains 2 fields: string and int and use that type instead of . So it results to the following correction:

var field1 =  (await result.ReadAsync<MyData>()).FirstOrDefault();

class MyData
{
string...

int ...
}

and it compiles but I get null for string and the proper data for int.

The query itself is correct, I tested it and it's fine. So the question is how to read the 2 columns?

Joe Doe
  • 11
  • 2

1 Answers1

1

Your second approach looks correct. Dapper by default maps on convention. Name of properties in your MyData class and the name of column should be same so that Dapper can map correctly.

So, your MyData class should look something like this:

class MyData
{
    string col1...
    int col2...
}

In case, your property names have to be different, you need to modify your query to use column alias something like below:

SELECT col1 AS MyProperty1, col2 AS MyProperty2 FROM Table1

Also note that in case of complex query/mapping, your table name should match with your name of POCO/Entity class.

There are ways to override the default mapping. Please refer this question for detailed discussion on Dapper's mapping.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141