Reading subset of the table using Dapper in C#

时光怂恿深爱的人放手 提交于 2019-12-24 08:53:41

问题


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?


回答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.



来源:https://stackoverflow.com/questions/52276390/reading-subset-of-the-table-using-dapper-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!