一千萬個為什麽

搜索

使用通過NHibernate獲得的自定義IList

我正在嘗試使用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做同樣的事情。不幸的是,我不知道如何使轉發器識別查詢結果的字段。

提前致謝!

最佳答案

NHibernate可以從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();

轉載註明原文: 使用通過NHibernate獲得的自定義IList