在C#中使用Dapper读取表的子集 [英] Reading subset of the table using Dapper in C#

查看:249
本文介绍了在C#中使用Dapper读取表的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Dapper,并且可以获取单个基本类型(int,十进制,字符串等)或任何db实体都可以,但是我只需要从表中读取2列,我在这里面临很多挑战:

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:

这是一个简单的查询:

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();

这是不可编译的。
我试图创建包含2个字段的类:string和int,并使用该类型代替。
因此导致以下更正:

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 ...
}

它可以编译,但是字符串为null,而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?

推荐答案

您的第二种方法看起来是正确的。默认情况下,Dapper按照约定进行映射。 MyData 类中的属性名称和列的名称应该相同,以便Dapper可以正确映射。

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.

因此,您的 MyData 类应如下所示:

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

还要注意对于复杂的查询/映射,表名称应与POCO /实体类的名称匹配。

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

有一些方法可以覆盖默认映射。请参考问题,以获取有关Dapper映射的详细讨论。

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

这篇关于在C#中使用Dapper读取表的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆