如何返回动态类型List< dynamic>与Dapper ORM
我已经使用Dapper.net已有一段时间了,它是一个非常好的ORM映射器,可以很好地与.Net动态类型一起使用.
I have been using Dapper.net for a while now and its a very good ORM mapper which works great with .Net dynamic types.
但是我注意到,当Dapper从数据库中检索数据时,它以DapperRow
类型返回.
But I noticed that when Dapper retrieves data from a database it returns as DapperRow
type.
是否可以通过其他任何方式(如System.Dynamic.ExpandoObject
)将其返回?
Is there are any way that I can return it in any other type Like System.Dynamic.ExpandoObject
?
DapperRow
对象旨在在行之间共享很多状态.例如,如果您获取40行,则列名称等仅一次存储.如果我们使用ExpandoObject
,则需要按行进行配置.因此,使用DapperRow
作为幕后实现细节是故意的.
The DapperRow
object is designed to share a lot of state between rows. For example, if you fetch 40 rows, the column names etc are only stored once. If we used ExpandoObject
, this would need to be configured per row. Hence, the use of DapperRow
as the behind-the-scenes implementation detail is a deliberate efficiency thing.
请注意,从dynamic
API返回的对象也可以转换为IDictionary<string,object>
.
Note that the object returned from the dynamic
APIs can also be cast as IDictionary<string,object>
.
但是,我愿意支持支持该词典用法的 other 类型-其中ExpandoObject
是其中之一.是的,它可以 进行更改,使得:
I would, however, be open to supporting other types that support this dictionary usage - of which ExpandoObject
is one. So yes, it could be changed such that:
var rows = conn.Query<ExpandoObject>(...);
有效.它只需要代码 support 即可,并且该代码目前不存在.因此,不,但也许会在将来的版本中."
works. It simply requires code to support it, and that code does not currently exist. So "no, but perhaps in a future build".
还请注意,您根本不需要使用DapperRow
.预期的更多方案是使用通用API来实现您自己的类型.
Note also that you don't need to use DapperRow
at all... The more expected scenario is to use the generic API to materialize your own types.