使用通过NHibernate获得的自定义IList

时间:2010-04-17 23:44:29

标签: c# .net nhibernate

我正在尝试使用C#和NHibernate 2.1在.NET中编写网页。

相关代码如下所示:

var whatevervar = session.CreateSQLQuery("select thread_topic, post_time, user_display_name, user_signature, user_avatar, post_topic, post_body from THREAD, [USER], POST, THREADPOST where THREADPOST.thread_id=" + id + " and THREADPOST.thread_id=THREAD.thread_id and [USER].user_id=POST.user_id and POST.post_id=THREADPOST.post_id ORDER BY post_time;").List();

(我曾尝试在HQL中使用连接,但由于HQL的不可读性,后来又回到了这个查询。)问题是我得到的结果与转发器不兼容。当我尝试这个时:

posts.DataSource = whatevervar.;
posts.DataBind();

......我明白了:

DataBinding: 'System.Object[]' does not contain a property with the name 'user_avatar'.

在早期的项目中,我使用LINQ to SQL实现了同样的目的,它看起来像这样:

var whatevervar = from threads in context.THREADs
                          join threadposts in context.THREADPOSTs
                            on threads.thread_id equals threadposts.thread_id
                          join posts1 in context.POSTs
                            on threadposts.post_id equals posts1.post_id
                          join users in context.USERs
                            on posts1.user_id equals users.user_id
                          orderby posts1.post_time
                          where threads.thread_id == int.Parse(id)
                          select new
                          {
                              threads.thread_topic,
                              posts1.post_time,
                              users.user_display_name,
                              users.user_signature,
                              users.user_avatar,
                              posts1.post_body,
                              posts1.post_topic
                          };

这很有效,现在我想对NHibernate做同样的事情。不幸的是,我不知道如何让转发器识别查询结果的字段。

提前致谢!

1 个答案:

答案 0 :(得分:3)

NHibernate可以return non-managed entities来自SQL查询。

创建一个非映射类来保存此查询的结果,并让NHibernate返回此类型的列表。

public class MyDTO
{
    public string thread_topic { get; set; }
    public DateTime post_time { get; set; }
    public string user_display_name { get; set; }
    public string user_signature { get; set; }
    public string user_avatar { get; set; }
    public string post_topic { get; set; }
    public string post_body { get; set; }
}

var whatevervar = session.CreateSQLQuery(@"select thread_topic, post_time, user_display_name, user_signature, user_avatar, post_topic, post_body
    from THREAD, [USER], POST, THREADPOST
    where THREADPOST.thread_id=" + id + " and THREADPOST.thread_id=THREAD.thread_id and [USER].user_id=POST.user_id and POST.post_id=THREADPOST.post_id
    ORDER BY post_time;")
.SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO)))
.List();