简体   繁体   English

ActiveRecord自定义SQL结果自动映射

[英]ActiveRecord custom SQL result automapping

In Castle ActiveRecord, I'm querying against the database with session.CreateSQLQuery(MyQueryString).List() 在Castle ActiveRecord中,我正在使用session.CreateSQLQuery(MyQueryString).List()查询数据库。

When the result columns of a query do not match 100% to the fields of any of my database tables, I cannot use an ActiveRecord-based class to automap the results into a strongly-typed object. 当查询的结果列与我的任何数据库表的字段都不匹配100%时,我将无法使用基于ActiveRecord的类将结果自动映射为强类型对象。

Is there a way to get the results of an ad hoc query mapped into a custom type (perhaps through ActiveRecord attributes on my target class?) without having to map field-by-field at in the query executing/processing code? 有没有一种方法可以将临时查询的结果映射到自定义类型(例如通过目标类上的ActiveRecord属性?)而不必在查询执行/处理代码中逐字段映射? I'm thinking something similar to: 我在想类似的东西:

MyQueryResultType[] results = session.CreateSQLQuery(MyQueryString).List().MapFieldsAs<MyQueryResultType>();

I haven't used ActiveRecord in awhile, but from what I remember, it uses NHibernate underneath, which can handle this. 我有一段时间没有使用ActiveRecord了,但是据我所记得,它在下面使用了NHibernate,它可以处理这个问题。 The following is some code shamelessly ripped from another Stack Overflow question/answer : 以下是从另一个Stack Overflow问题/答案中偷偷摸摸地摘录的一些代码:

IList<MyObj> reults = Session.CreateQuery("select r.feedname as feedname, count(r.feedurl) as feedcount from rsssubscriptions r group by r.feedname")
                                                .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(MyObj)))
                                                .List<MyObj>();

While there isn't a "MapFieldAs" function, there is a "SetResultTransformer" function. 虽然没有“ MapFieldAs”功能,但有“ SetResultTransformer”功能。 This function allows you to pass an object that describes what should be done once you get the results back from the database. 此函数允许您传递一个对象,该对象描述从数据库取回结果后应执行的操作。 In order to tell the query to take the data and map the columns onto a list of strongly-typed objects, you would have to define a transformer object that does just that. 为了告诉查询获取数据并将列映射到强类型对象的列表上,您必须定义一个可以执行此操作的转换器对象。 Luckily, NHibernate also has a generic transformer object that you can use (NHibernate.Transform.Transformers.AliasToBean). 幸运的是,NHibernate还有一个可以使用的通用转换器对象(NHibernate.Transform.Transformers.AliasToBean)。

Here are some answers on stack overflow with examples: 以下是一些有关堆栈溢出的答案,并提供示例:

NHibernate: returning a strongly typed list having applied an aggregate function NHibernate:返回已应用聚合函数的强类型列表

Using Unmapped Class with NHibernate Named Query 将未映射的类与NHibernate命名查询一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM